这对我来说似乎是个陷阱,我无法弄明白
>>> from collections import Counter
>>> tree = [Counter()]*3
>>> tree
[Counter(), Counter(), Counter()]
>>> tree[0][1]+=1
>>> tree
[Counter({1: 1}), Counter({1: 1}), Counter({1: 1})]
为什么更新一个计数器会更新所有内容?
答案 0 :(得分:5)
使用[x] * 3
,列表引用相同的项目(x
)三次。
>>> from collections import Counter
>>> tree = [Counter()] * 3
>>> tree[0] is tree[1]
True
>>> tree[0] is tree[2]
True
>>> another_counter = Counter()
>>> tree[0] is another_counter
False
>>> for counter in tree: print id(counter)
...
40383192
40383192
40383192
使用列表理解为Waleed Khan评论。
>>> tree = [Counter() for _ in range(3)]
>>> tree[0] is tree[1]
False
>>> tree[0] is tree[2]
False
>>> for counter in tree: print id(counter)
...
40383800
40384104
40384408
答案 1 :(得分:1)
[Counter()]*3
生成一个包含相同 Counter
实例3次的列表。你可以使用
[Counter() for _ in xrange(3)]
创建一个包含3个独立Counter
s。
>>> from collections import Counter
>>> tree = [Counter() for _ in xrange(3)]
>>> tree[0][1] += 1
>>> tree
[Counter({1: 1}), Counter(), Counter()]
通常,在将元素可变的列表相乘时,您应该谨慎。
答案 2 :(得分:1)
tree = [Counter()]*3
创建一个计数器和三个引用它;你可以把它写成:
c = Counter()
tree = [c, c, c]
您需要三个计数器:
>>> from collections import Counter
>>> tree = [Counter() for _ in range(3)]
>>> tree[0][1]+=1
>>> tree
[Counter({1: 1}), Counter(), Counter()]
>>>