python中的列表行为是不可理解的

2024-03-28 17:24:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我想理解python中的小片段:

>>> x = ['foo', [1,2,3], 10.4]
>>> y = list(x)
>>> y[0]
'foo'
>>> y[0] = "fooooooo"
>>> y[1]
[1, 2, 3]
>>> y[1][0]=4
>>> print x
['foo', [4, 2, 3], 10.4]
>>> print y
['fooooooo', [4, 2, 3], 10.4]
>>> z = ['foo', [1,2,3], 10.4]
>>> x = ['foo', [1,2,3], 10.4]
>>> y = list(x)
>>> y[0] = "fooooooo"
>>> y[1]
[1, 2, 3]
>>> y[1][0]=4
>>> print x
['foo', [4, 2, 3], 10.4]
>>> print y
['fooooooo', [4, 2, 3], 10.4]
>>> print z
['foo', [1, 2, 3], 10.4]
>>> y = list(z)
>>> y[1][0]=6
>>> print y
['foo', [6, 2, 3], 10.4]
>>> y = list(z)
>>> print z
['foo', [6, 2, 3], 10.4]
>>> print x
['foo', [4, 2, 3], 10.4]

这是怎么回事。 如果将y的list元素改为x,这可能是python的一个基本概念,但我仍然没有掌握这个概念


Tags: 概念元素foolistprintfooooooo
3条回答

我猜你唯一困惑的是设置一个变量的嵌套列表的元素会改变所有其他变量的嵌套列表。原因很简单:Python在每个变量中使用相同的嵌套列表(比如,完全相同的内存)。当您说y = list(x)时,Python将x的所有原子元素复制到y中,但只复制对嵌套列表的引用。因为相同的嵌套列表到处都在使用,所以修改它一个地方就会修改它。你知道吗

通过玩l1 = [0]*3l2 = [[0]]*3,您也可以看到类似的行为;l1l2行为方式之间的差异是您观察到的行为的另一个例子。你知道吗

y = list(x)

上面的语句创建列表x的浅层副本。你知道吗

documentation

A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.

在这里,您确实获得了一个新对象y,但是由于其中的列表是一个可变对象,因此您获得了对原始对象的引用。而且,如果继续创建这些浅层副本,列表对象将在所有副本之间共享。你知道吗

您可以使用id检查它:

>>> id(x)
140183460314288
>>> id(y)
140183460372992        # this is different from y
>>> id(x[1])
140183460314864
>>> id(y[1])           # this is same as x[1] 
140183460314864
>>> y1 = list(y)       # another shallow copy from y
>>> id(y1[1]) 
140183460314864        # this is still same  

如果预期的行为确实需要修改y的内容而不影响x,则需要执行deepcopy

>>> >>> from copy import deepcopy
>>> z = deepcopy(x)
>>> id(z[1])
140183460405400        # this is different now because of deepcopy

您可以看到这个id与id(x[1])不同,现在如果您尝试修改内容,它们将不会反映在x。你知道吗

>>> x = ['foo', [1,2,3], 10.4]
>>> y = list(x)

yx的副本。y[1]包含列表[1,2,3]引用的副本。所以y[1]x[1]是对同一列表的两个引用。你知道吗

相关问题 更多 >