3 回答

TA貢獻1898條經驗 獲得超8個贊
這樣做 [[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]]
整數/浮點數是不可變的,而列表則是可變的:
>>> 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)

TA貢獻1811條經驗 獲得超5個贊
該列表test
包含同一列表的多個迭代,因此一個更改(如您通過重新分配的第一個元素所做的更改test[0]
)將反映在所有其他更改中。嘗試以下方法:
[[0.0]*10 for _ in xrange(10)] # or `range` in Python 3.x
當然,如果您只擁有,就不必擔心這一點[0.0] * 10
,因為這會創建一個整數列表,這些整數都無法改變。另一方面,列表確實是可變的。
添加回答
舉報