3 回答

TA貢獻(xiàn)1898條經(jīng)驗(yàn) 獲得超8個(gè)贊
這樣做 [[0.0] * 10] * 10實(shí)際上會(huì)創(chuàng)建同一列表的多個(gè)副本,因此修改一個(gè)副本將影響所有副本:
>>> 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]
嘗試這個(gè):
>>> 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]]
整數(shù)/浮點(diǎn)數(shù)是不可變的,而列表則是可變的:
>>> 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貢獻(xiàn)1811條經(jīng)驗(yàn) 獲得超5個(gè)贊
該列表test
包含同一列表的多個(gè)迭代,因此一個(gè)更改(如您通過(guò)重新分配的第一個(gè)元素所做的更改test[0]
)將反映在所有其他更改中。嘗試以下方法:
[[0.0]*10 for _ in xrange(10)] # or `range` in Python 3.x
當(dāng)然,如果您只擁有,就不必?fù)?dān)心這一點(diǎn)[0.0] * 10
,因?yàn)檫@會(huì)創(chuàng)建一個(gè)整數(shù)列表,這些整數(shù)都無(wú)法改變。另一方面,列表確實(shí)是可變的。
添加回答
舉報(bào)