即使您描述的行爲(如您所描述的那樣)是不可能的,但我仍會對此採取刺探行動。
如果您創建一個列表,您需要確保每個子列表都是不同的列表。考慮:
a = []
b = [a, a]
這裏我創建了一個列表,其中兩個子列表都是完全相同的列表。如果我改變它,它會出現在兩個。例如: -
>>> a = []
>>> b = [a, a]
>>> b[0].append(1)
>>> b
[[1], [1]]
,你會經常看到一個列表這種行爲使用*
操作初始化:
a = [[None]*7]*7
例如
>>> a = [[None]*7]*7
>>> a
[[None, None, None, None, None, None, None], [None, None, None, None, None, None, None], [None, None, None, None, None, None, None], [None, None, None, None, None, None, None], [None, None, None, None, None, None, None], [None, None, None, None, None, None, None], [None, None, None, None, None, None, None]]
>>> a[0][1] = 3
>>> a
[[None, 3, None, None, None, None, None], [None, 3, None, None, None, None, None], [None, 3, None, None, None, None, None], [None, 3, None, None, None, None, None], [None, 3, None, None, None, None, None], [None, 3, None, None, None, None, None], [None, 3, None, None, None, None, None]]
,修復方法是外列表中不使用*
7(內部列表是OK,因爲None
是不可改變的)
a = [[None]*7 for _ in range(7)]
如:
>>> a = [[None]*7 for _ in range(7)]
>>> a[0][1] = 3
>>> a
[[None, 3, None, None, None, None, None], [None, None, None, None, None, None, None], [None, None, None, None, None, None, None], [None, None, None, None, None, None, None], [None, None, None, None, None, None, None], [None, None, None, None, None, None, None], [None, None, None, None, None, None, None]]
不可再現之前。 – thefourtheye
我無法複製它。你能不能在python解釋器中運行所有這些?你使用哪種Python? – lpapp
即使您有NumPy矩陣或對同一列表的多個引用,這也沒有任何意義。請給我們一個真正的口譯員會議嗎? – user2357112