2012-11-01 53 views
0

可能重复:
Unexpected feature in a Python list of lists环路改变矩阵值给出了奇怪的结果

我有11充满0的9矩阵我要让每一个的第一要素行,每列的第一个元素的分数比前一分小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中的所有行?

+1

@senderle - 好的发现。这是一个很常见的问题,但标题遍布整个地方,当我看到它出现时很难追查一个副本。 – mgilson

+0

@mgilson,这确实很难。在这种情况下,所有功劳都应该到[flebool](http://stackoverflow.com/a/13176124/577088)! – senderle

回答

1

这是因为你创建列表清单的方式actully产生包含在它同一个列表对象列表,即同一id(),改变一个实际上改变了其他人也:

In [4]: x_row = [0]*(5+1) 

In [5]: matrix = [x_row]*(7+1) 

In [6]: [id(x) for x in matrix] 
Out[6]:       #same id()'s, means all are same object 
[172797804, 
172797804, 
172797804, 
172797804, 
172797804, 
172797804, 
172797804, 
172797804] 

In [20]: matrix[0][1]=5 #changed only one 

In [21]: matrix   #but it changed all 
Out[21]:  
[[0, 5, 0, 0, 0, 0], 
 [0, 5, 0, 0, 0, 0], 
 [0, 5, 0, 0, 0, 0], 
 [0, 5, 0, 0, 0, 0], 
 [0, 5, 0, 0, 0, 0], 
 [0, 5, 0, 0, 0, 0], 
 [0, 5, 0, 0, 0, 0], 
 [0, 5, 0, 0, 0, 0]] 

你应该创建你的矩阵这种方式来避免:

In [12]: matrix=[[0]*6 for _ in range(9)] 

In [13]: [id(x) for x in matrix] 
Out[13]:       #different id()'s, so different objects 
[172796428,    
172796812, 
172796364, 
172796268, 
172796204, 
172796140, 
172796076, 
172795980, 
172795916] 

In [23]: matrix[0][1]=5 #changed only one 

In [24]: matrix   #results as expected 
Out[24]:  
[[0, 5, 0, 0, 0, 0], 
 [0, 0, 0, 0, 0, 0], 
 [0, 0, 0, 0, 0, 0], 
 [0, 0, 0, 0, 0, 0], 
 [0, 0, 0, 0, 0, 0], 
 [0, 0, 0, 0, 0, 0], 
 [0, 0, 0, 0, 0, 0], 
 [0, 0, 0, 0, 0, 0], 
 [0, 0, 0, 0, 0, 0]] 
+0

谢谢,使矩阵以这种方式工作。我会尽我所能接受。 –

+0

@NiekdeKlein很高兴帮助,你可以接受解决方案,如果它为你工作。 –