可能重复:
Python 列表中的意外功能
我有一个用 9 x 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]
为什么它将 column[0]*-2 的最后一个值提供给所有行?