简体   繁体   English

Python中这两个数组声明之间有什么区别?

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

What is the difference between these two array declarations in Python? Python中这两个数组声明之间有什么区别?

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

They have nothing in common in fact. 它们实际上没有任何共同之处。 The second is a numpy 2D array. 第二个是一个numpy的二维数组。 The first is not anything useful - it's an array of 100 items, each one of which is a reference to a SINGLE array of 100 zeroes: 第一个没有什么用,它是一个包含100个项的数组,每个项都是对100个零的SINGLE数组的引用:

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

This prints '222'! 这将打印“ 222”!

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

This prints '0'! 打印“ 0”!

Well, for once, the first one is dangerously wrong. 好吧,第一次,第一个错误是危险的 See this: 看到这个:

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]]

It happens because the way you declared table , the sub-list is duplicated all over again. 发生这种情况是因为您声明table ,sub-list的方式再次重复了一次。 See this FAQ for info on doing this correctly. 有关正确执行此操作的信息,请参见此常见问题解答

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM