2014-10-27 70 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) 
相关问题