2014-10-27 42 views
0
M = [[3.5, 1.0, 9.2, 4.0], [0, 0, 0, 0], [3.0, 1.0, 8.0, -2.0]] 
c_idx = 2 
for count4 in range(len(M)): 
    for count5 in range(len(M[count4])): 
     if M[count4].index(M[count4][count5]) == c_idx : 
      M[count4] = M[count4][ :c_idx] + [0] + M[count4][c_idx+1 : ] 
     count4 += 1 
    count5 += 1 
print(M) 

所以我試圖爲列表M重寫一個特定位置的元素。但它顯示了我一個錯誤:如何在python中重寫嵌套列表中某個元素的值?

if M[count4].index(M[count4][count5]) == c_idx : 
IndexError: list index out of range 

結果應該是這樣的:

[[3.5, 1.0, 0, 4.0], [0, 0, 0, 0], [3.0, 1.0, 0, -2.0]] 

我看不出我做錯了。幫助我的人們!

+0

你能解釋/顯示你的預期結果是什麼嗎? – CoryKramer 2014-10-27 11:49:16

+0

[[3.5,1.0,0,4.0],[0,0,0,0],[3.0,1.0,0.0-2.0]] – 2014-10-27 11:52:24

回答

0

只是刪除count4 +=1count5 +=1

M = [[3.5, 1.0, 9.2, 4.0], [0, 0, 0, 0], [3.0, 1.0, 8.0, -2.0]] 
c_idx = 2 
for count4 in range(len(M)): 
    for count5 in range(len(M[count4])): 
     if M[count4].index(M[count4][count5]) == c_idx : 
      M[count4] = M[count4][ :c_idx] + [0] + M[count4][c_idx+1 : ] 

print(M) 
[[3.5, 1.0, 0, 4.0], [0, 0, 0, 0], [3.0, 1.0, 0, -2.0]] 

for/looprange已經做了+=1你。 雖然在其他答案中提到了很多更清潔的方法。

0
def replaceElement(l, index, element): 
    for row in l: 
     row[index] = element 
    return l 

M = [[3.5, 1.0, 9.2, 4.0], [0, 0, 0, 0], [3.0, 1.0, 8.0, -2.0]] 
c_idx = 2 
M = replaceElement(M, c_idx, 0) 

>>> M 
[[3.5, 1.0, 0, 4.0], [0, 0, 0, 0], [3.0, 1.0, 0, -2.0]] 
0
M = [[3.5, 1.0, 9.2, 4.0], [0, 0, 0, 0], [3.0, 1.0, 8.0, -2.0]] 

c_idx = 2 
for sublist in M: 
    sublist[c_idx] = 0 # change the third element to 0 in each sublist 
print(M) 
相關問題