【问题标题】:Python list simultaneous update [duplicate]Python列表同时更新[重复]
【发布时间】:2013-07-29 18:58:59
【问题描述】:

这对我来说似乎是一个陷阱,我想不通

>>> 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})]

为什么更新一个 Counter 会更新所有内容?

【问题讨论】:

  • 因为[Counter()]*3这一行。您没有创建 3 个独特的计数器。您正在创建一个列表,其中包含对同一 Counter 对象的三个引用。
  • 您有一个列表,其中包含对同一计数器的三个引用。请尝试使用列表推导。

标签: python python-2.7


【解决方案1】:

使用[x] * 3,列表引用同一个项目(x) 3 次。

>>> 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

【讨论】:

  • 另外,for counter in tree: print id(counter) 应该可以更好地理解。
  • @limelights,谢谢你的建议。我添加了那个。
【解决方案2】:

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()]
>>> 

【讨论】:

    【解决方案3】:

    [Counter()]*3 生成一个列表,其中包含 same Counter 实例 3 次。你可以使用

    [Counter() for _ in xrange(3)]
    

    创建一个包含 3 个独立 Counters 的列表。

    >>> from collections import Counter
    >>> tree = [Counter() for _ in xrange(3)]
    >>> tree[0][1] += 1
    >>> tree
    [Counter({1: 1}), Counter(), Counter()]
    

    一般来说,在将元素可变的列表相乘时应该小心。

    【讨论】:

      猜你喜欢
      • 2017-10-16
      • 1970-01-01
      • 2013-03-26
      • 1970-01-01
      • 1970-01-01
      • 2018-07-11
      • 1970-01-01
      • 2015-02-24
      • 1970-01-01
      相关资源
      最近更新 更多