我编写了一个非常简单的代码来初始化矩阵,但是我得到了一些非常意外的行为,这是我运行的确切代码:
n = 2
b = [ ([0.0] * n) ] * n
c = [ ([0.0] * n) ] * n
a = [ [1.0, 2.0, 3.0], [2.0, 1.0, 3.0]]
....
print(c[0])
print(c[1])
for i in range(0, n):
b[i][0] = a[i][0] #this one is initialized as expected
c[0][i] = a[0][i] / b[0][0] # notice that c[1] isn't touched here in any way but when I print it out it is initialized to [1.0 1.0]
print("")
print(c[0])
print(c[1])
但这些是我从print
语句得到的结果:
[0.0, 0.0]
[0.0, 0.0]
[1.0, 1.0]
[1.0, 1.0]
(只应初始化第一行,而不是所有元素)
我在Python 2.7.2
上运行Windows
。
这里有什么我想念的吗?
答案 0 :(得分:5)
使用[...] * 3
不会创建3个副本,但会重复使用同一个对象3次。因此,对一个索引的任何更改都将镜像到另一个索引:
>>> a = [[1] * 2] * 3
>>> a
[[1, 1], [1, 1], [1, 1]]
>>> a[0][1] = 3
>>> a
[[1, 3], [1, 3], [1, 3]]
最好像这样初始化:
a = [[1] * 2 for i in range(3)]