簡體   English   中英

Python中這兩個數組聲明之間有什么區別?

[英]What is the difference between these two array declarations in Python?

Python中這兩個數組聲明之間有什么區別?

table = [[0]*100]*100
table = numpy.zeros([100,100], int)

它們實際上沒有任何共同之處。 第二個是一個numpy的二維數組。 第一個沒有什么用,它是一個包含100個項的數組,每個項都是對100個零的SINGLE數組的引用:

table = [[0]*100]*100
table[1][0]=222
print table[0][0]

這將打印“ 222”!

table = numpy.zeros([100,100], int)
table[1][0]=222
print table[0][0]

打印“ 0”!

好吧,第一次,第一個錯誤是危險的 看到這個:

In [8]: table = [[0]*2]*10

In [9]: table
Out[9]: 
[[0, 0],
 [0, 0],
 [0, 0],
 [0, 0],
 [0, 0],
 [0, 0],
 [0, 0],
 [0, 0],
 [0, 0],
 [0, 0]]

In [10]: table[0][1] = 5

In [11]: table
Out[11]: 
[[0, 5],
 [0, 5],
 [0, 5],
 [0, 5],
 [0, 5],
 [0, 5],
 [0, 5],
 [0, 5],
 [0, 5],
 [0, 5]]

發生這種情況是因為您聲明table ,sub-list的方式再次重復了一次。 有關正確執行此操作的信息,請參見此常見問題解答

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM