list的*運算使用過程中遇到的問題
阿新 • • 發佈:2018-12-05
目的:
想生成一個[[],[],[]] 這樣的列表,
所以就 [[]]*3 這樣做了,但是這樣做會有問題,這樣list中的三個list其實是同一個list。
例如:a=[[]]*3,然後a[0].append(1),
然後a就變成這樣了:[[1],[1],[1]]
驗證一下,發現表示式 a[0] is a[1] 的值為True。
如何解決呢,可以用列表生成器:a=[[] for i in range(3)]
這應該像是值型別和引用型別的區別,但是翻看python的文件時沒發現有類似的說法,不過在翻看文件時發現裡面提到了這個情形:
https://docs.python.org/3.6/library/stdtypes.html
內容摘錄如下:
Note that items in the sequence s are not copied; they are referenced multiple times. This often haunts new Python programmers; consider:
>>> lists = [[]] * 3 >>> lists [[], [], []] >>> lists[0].append(3) >>> lists [[3], [3], [3]]
What has happened is that [[]]
is a one-element list containing an empty list, so all three elements of [[]] * 3
are references to this single empty list. Modifying any of the elements of lists
modifies this single list. You can create a list of different lists this way:
>>> lists = [[] for i in range(3)] >>> lists[0].append(3) >>> lists[1].append(5) >>> lists[2].append(7) >>> lists [[3], [5], [7]]
參考文獻: zhang