【问题标题】:Why adding a element to a set within dictionary, all sets is being modified? (Python) [duplicate]为什么向字典中的集合添加元素,所有集合都被修改? (Python)[重复]
【发布时间】:2014-09-07 09:41:32
【问题描述】:

我正在尝试将一个元素添加到 Python 字典中的集合中,但是当我使用 mydictionary[index].update([newelement]) 时,所有字典都将使用新元素进行更新。这里是 python 控制台命令和输出来演示我在说什么:

>>> graph=dict.fromkeys(range(10),set([]))
>>> graph
{0: set([]), 1: set([]), 2: set([]), 3: set([]), 4: set([]), 5: set([]), 6: set([]), 7: set([]), 8: set([]), 9: set([])}
>>> graph[0].update([1])
>>> graph
{0: set([1]), 1: set([1]), 2: set([1]), 3: set([1]), 4: set([1]), 5: set([1]), 6: set([1]), 7: set([1]), 8: set([1]), 9: set([1])}

那么为什么不只更新graph[0] 的条目呢?

我真的很想专门找一个有这个问题的话题,但是没有找到。

Obs:带数字的括号是python控制台中的命令。

【问题讨论】:

    标签: python dictionary set


    【解决方案1】:

    dict.fromkeys 创建一个字典,其中的键来自您输入的第一项,而值第二个元素。换句话说,所有的值都引用同一个对象。

    这与 if 相同:

    a = set()
    b = a
    b.add('foo')
    print a
    

    在这种情况下,您会看到ab 都有一个元素'foo'。现在看看他们的 ID:

    print id(a)
    print id(b)
    

    注意它是同一个数字,因为它们是同一个对象。

    【讨论】:

      【解决方案2】:

      变量graph 不是 10 个集合,它是一个包含十个元素的字典,其中每个值都引用 same 集合。因此,修改一组内容会修改所有内容。

      >>> graph=dict.fromkeys(range(10),set([]))
      >>> id(graph[0]), id(graph[1])
      (140681644256512, 140681644256512)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-01-13
        • 2015-01-22
        • 1970-01-01
        • 2022-01-01
        • 1970-01-01
        相关资源
        最近更新 更多