![](/img/trans.png)
[英]What's the difference between these two ways of implementing `on duplication increment`?
[英]What's the difference between these two ways of initializing an array?
matrix = [[0]*1005]*1005
和
matrix = [[0 for _ in range(1005)] for _ in range(1005)]
我發現如果我將前者用於初始數組,並運行matrix[1][1] = 1
,它將把每一行中的第二列設置為1。第二列按我的意願執行。 我不知道為什么嗎?
[[0] * 1005] * 1005
將創建一個包含1005個引用的數組,該數組具有1005個零。 它們都是相同的參考,因此更改一個將更改所有其他。 您可以將工作代碼縮短為:
matrix = [[0] * 1005 for _ in range(1005)]
實際上,這幾乎是任何人都對列表乘法語法發出的唯一警告:)
只是為了擴展已經說過的話
a = [[0]] * 5
print a # [[0], [0], [0], [0], [0]]
a[0][0] = 1
print a # [[1], [1], [1], [1], [1]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.