Python中的循环副作用

use*_*997 0 python

我编写了一个非常简单的代码来初始化矩阵,但是我得到了一些非常意外的行为,这是我运行的确切代码:

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])
Run Code Online (Sandbox Code Playgroud)

但这些是我从print陈述中得到的结果:

[0.0, 0.0]
[0.0, 0.0]

[1.0, 1.0]
[1.0, 1.0] 
Run Code Online (Sandbox Code Playgroud)

(只应初始化第一行,而不是所有元素)

我跑Python 2.7.2了Windows.这里有什么我想念的吗?

Jun*_*sor 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]]
Run Code Online (Sandbox Code Playgroud)

最好像这样初始化:

a = [[1] * 2 for i in range(3)]
Run Code Online (Sandbox Code Playgroud)