嵌入式for循环在python中的意外行为

时间:2012-05-31 09:24:00

标签: python

非常简单的代码嵌套示例:

所有代码都会创建一个初始化为零的列表列表。 它遍历列表行和列,每个位置都有一个值。 出于某种原因,在打印最终矢量时,每列的2D列表的最后一行是重复的。

Number_of_channels=2
Coefficients_per_channel=3

coefficient_array=[[0]*Coefficients_per_channel]*Number_of_channels 
print coefficient_array

for channel in range(Number_of_channels):
    for coeff in range(Coefficients_per_channel):
        coefficient_array[channel][coeff]=coeff*channel
        print coefficient_array[channel][coeff]

print coefficient_array

输出:

[[0, 0, 0], [0, 0, 0]]
0
0
0
0
1
2
[[0, 1, 2], [0, 1, 2]]

我其实期望:

[[0, 0, 0], [0, 1, 2]]

任何人都知道这是怎么回事?

3 个答案:

答案 0 :(得分:5)

您只复制外部列表,但该列表的值保持不变。因此,所有(两个)外部列表都包含对同一内部可变列表的引用。

>>> example = [[1, 2, 3]]
>>> example *= 2
>>> example
[[1, 2, 3], [1, 2, 3]]
>>> example[0][0] = 5
[[5, 2, 3], [5, 2, 3]]
>>> example[0] is example[1]
True

最好在循环中创建内部列表:

coefficient_array=[[0]*Coefficients_per_channel for i in xrange(Number_of_channels)]

或者再次用python提示说明:

>>> example = [[i, i, i] for i in xrange(2)]
>>> example
[[0, 0, 0], [1, 1, 1]]
>>> example[0][0] = 5
>>> example
[[5, 0, 0], [1, 1, 1]]
>>> example[0] is example[1]
False

答案 1 :(得分:1)

使用

coefficient_array=[[0]*Coefficients_per_channel]*Number_of_channels

您对同一个对象进行重复引用:

coefficient_array[0] is coefficient_array[1]

评估为True

相反,使用

构建数组
[[coeff*channel for coeff in range(Coefficients_per_channel)] for channel in range(Number_of_channels)]

答案 2 :(得分:0)

请改为尝试:

coefficient_array=[0]*Number_of_channels 
print coefficient_array

for channel in range(Number_of_channels):
    coefficient_array[channel] = [0] * Coefficients_per_channel
    for coeff in range(Coefficients_per_channel):
        coefficient_array[channel][coeff]=coeff*channel
        print (channel, coeff)
        print coefficient_array[channel][coeff]

print coefficient_array