1

I noticed something odd while helping a collegue with his Python 2.7 script. He has a dictionary with lists as the dictionary values. He was assigning the dictionary values to a new variable and then performing some edits to the list. The odd part that got me was the list changes in the new variable were also being reflected in the dictionary. I repeated a simple example in the shell and I posted it below. I also tried the same thing but with a string as the dictionary value, but to no effect. Is there something I am missing here or is this some sort of bug? Thanks.

>>> dict1 = {}
>>> dict1['foo'] = [1,2,3]
>>> print dict1     
 {'foo': [1, 2, 3]}    
>>> bar = dict1['foo']
>>> bar.append(4)
>>> print dict1    
 {'foo': [1, 2, 3, 4]}

In the example above I would have expected the 4 to be appended to bar and the value of 'foo' to remain [1,2,3].

4

1 回答 1

3

您不会获得列表的副本,而是获得对列表本身的引用。由于列表是可变的,因此该行为完全是意料之中的。

将此与使用指向列表的第二个变量进行比较:

>>> a = [1, 2, 3]
>>> b = a
>>> b.append(4)
>>> a
[1, 2, 3, 4]

如果您想拥有一个独立的列表,请制作一份副本:

>>> c = list(a)
>>> c.append(5)
>>> c
[1, 2, 3, 4, 5]
>>> a
[1, 2, 3, 4]

制作副本的另一种方法是使用完整列表切片:

>>> c = a[:]
于 2013-01-09T16:23:18.243 回答