gpt4 book ai didi

python - 在 Python : How to make deep copies of each row? 中初始化二维列表

转载 作者:太空狗 更新时间:2023-10-30 00:50:52 35 4
gpt4 key购买 nike

假设我想用全 0 初始化一个 2D Python 列表,我会这样做:

test = [[0.0] * 10] * 10

然后我开始修改第一个列表中的值...

test[0][0] = 1.0

但是由于某种原因,这会影响所有列表的第一项:

print test

[[1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]]

这是怎么回事?为什么它对内部列表进行深拷贝,而对外部列表进行浅拷贝?

最佳答案

执行[[0.0] * 10] * 10实际上会创建同一个列表的多个副本,因此修改其中一个会影响所有副本:

>>> test = [[0.0] * 10] * 10
>>> [id(x) for x in test] #see all IDs are same
[3065020524L, 3065020524L, 3065020524L, 3065020524L, 3065020524L, 3065020524L, 3065020524L, 3065020524L, 3065020524L, 3065020524L]

试试这个:

>>> test = [[0.0]*10 for _ in xrange(10)]
>>> test[0][0] = 1.0
>>> test
[[1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]]

整数/ float 是不可变的,而列表是可变的:

>>> x = y = []
>>> x is y # Both point to the same object
True
>>> x.append(1) # list.extend modifies a list in-place
>>> x,y # both references to [] can see the modification
([1], [1])
>>> x = y = 1
>>> x is y #both points to the same object
True
>>> x+=1 # only x gets modified, it now points to a new object 2
>>> x,y # y still points to the same object 1
(2, 1)

关于python - 在 Python : How to make deep copies of each row? 中初始化二维列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17099121/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com