[英]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.