根据您的评论,您可能在将列表添加到字典后对其进行了修改。在 python 中,几乎所有东西,例如。变量名、列表项、字典项等只是引用值,而不包含它们本身。列表是可变的,因此如果您将一个添加到字典中,然后通过另一个名称修改列表,则更改也会显示在字典中。
那是:
# Both names refer to the same list
a = [1]
b = a # make B refer to the same list than A
a[0] = 2 # modify the list that both A and B now refer to
print a # prints: [2]
print b # prints: [2]
# The value in the dictionary refers to the same list as A
a = [1]
b = {'key': a}
a[0] = 2
print a # prints: [2]
print b # prints: {'key': [2]}
但是,请注意,为变量分配新值不会更改引用的值:
# Names refer to different lists
a = [1]
b = a # make B refer to the same list than A
a = [2] # make A refer to a new list
print a # prints [2]
print b # prints [1]
您创建了一个新列表,并将旧列表中的项目“手动”一一复制到新列表中。这行得通,但它占用了大量空间,并且有一种更简单的方法可以通过使用切片来实现。切片返回一个新列表,所以如果你不指定开始和结束位置,即。通过 write list_variable[:]
,它本质上只是返回原始列表的副本。
也就是修改原来的例子:
# Names refer to different lists
a = [1]
b = a[:] # make B refer to a copy of the list that A refers to
a[0] = 2
print a # prints: [2]
print b # prints: [1]
# The value in the dictionary refers to a different list than A
a = [1]
b = {'key': a[:]}
a[0] = 2
print a # prints: [2]
print b # prints: {'key': [1]}