2

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

代码所做的只是创建一个初始化为零的列表列表。它遍历列表的行和列,每个位置都有一个值。由于某种原因,当打印最终向量时,每行都会复制 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]]

有人知道这是怎么发生的吗?

4

3 回答 3

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
于 2012-05-31T09:26:51.213 回答
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)]
于 2012-05-31T09:39:53.423 回答
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
于 2012-05-31T09:31:08.213 回答