Possible Duplicate:
Unexpected feature in a Python list of lists
我有一个矩阵,里面有9乘11的0。我想让每一行的第一个元素和每一列的第一个元素的得分比前一个元素少-2,所以:
[[0, -2, -4], [-2, 0, 0], [-4, 0, 0]]
为此,我使用以下代码:
# make a matrix of length seq1_len by seq2_len filled with 0's\
x_row = [0]*(seq1_len+1)
matrix = [x_row]*(seq2_len+1)
# all 0's is okay for local and semi-local, but global needs 0, -2, -4 etc at first elmenents
# because of number problems need to make a new matrix
if align_type == 'global':
for column in enumerate(matrix):
print column[0]*-2
matrix[column[0]][0] = column[0]*-2
for i in matrix:
print i
结果:
0
-2
-4
-6
-8
-10
-12
-14
-16
[-16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[-16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[-16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[-16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[-16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[-16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[-16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[-16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[-16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
为什么它将列[0]*-2的最后一个值赋给所有行?你知道吗
尝试运行以下代码:
x_row = [0]*(seq1_len+1)
matrix = [x_row]*(seq2_len+1)
matrix[4][5]=5
print matrix
你看5号已经扩散了。这是因为第二行代码复制了相同的数据。看到这个了吗
List of lists changes reflected across sublists unexpectedly
这是因为创建列表列表的方式实际上会生成一个列表,其中包含相同的列表对象,即相同的
id()
,更改一个对象实际上也会更改其他对象:您应该这样创建矩阵以避免:
相关问题 更多 >
编程相关推荐