【问题标题】:Strange behaviour when appending items to lists inside dictionaries in python [duplicate]将项目附加到python中字典内的列表时的奇怪行为[重复]
【发布时间】:2014-12-23 13:12:20
【问题描述】:

我有一个由 201 个整数键 (0..200) 索引的字典。这些键中的每一个的值都是一个列表。使用以下代码生成:

dictionary=dict.fromkeys(range201,[])

当我尝试将项目附加到属于一个特定索引的列表时,我会遇到这种奇怪的行为,如果我这样做:

dictionary[1].append("foo")

我希望这样:

>>dictionary
{0:[], 1:["foo"],2:[],...}

但我最终得到了这个:

>>dictionary
{0:["foo"], 1:["foo"],2:["foo"],...}

为了澄清执行操作的上下文,我列举了一个可以是Nonefloat 的值列表,我想跳过None 并将float 附加到枚举索引对应的列表:

for i, value in enumerate(valuesList):
    if value is None:
        continue
    dictionary[i].append(value)

这种行为与我使用的整数索引无关,并且我最终在所有索引处得到相同的值。我可以使用列表列表并达到我认为的相同结果。但我想了解这种行为。

【问题讨论】:

标签: python list python-2.7 dictionary append


【解决方案1】:

这是正常行为。字典的所有条目都使用对同一列表的引用进行了初始化。因此,当使用一个键附加元素时,由于所有键都指向同一个列表,因此修改将应用于 dic 的所有条目。

试试这个:

dictionary={}
for i in range(201):
    #the loop make the list.__init__() (i.e. the []) being called 200 times
    dictionary[i] = []

dictionary[1].append("foo")
print dictionary

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-09
    • 2014-12-09
    • 2015-07-15
    • 1970-01-01
    • 1970-01-01
    • 2019-01-04
    相关资源
    最近更新 更多