如何在python中重写嵌套列表中某个元素的值?
因此,我试图重写列表中某个位置的元素,m。但它显示了一个错误:如何在python中重写嵌套列表中某个元素的值?,python,list,indexing,nested,rewrite,Python,List,Indexing,Nested,Rewrite,因此,我试图重写列表中某个位置的元素,m。但它显示了一个错误: 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[cou
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)
结果应该是这样的:
if M[count4].index(M[count4][count5]) == c_idx :
IndexError: list index out of range
我看不出我做错了什么。帮帮我,伙计们 只需删除
count4+=1
和count5+=1
[[3.5, 1.0, 0, 4.0], [0, 0, 0, 0], [3.0, 1.0, 0, -2.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)
范围中的for/loop
已经为您执行了+=1
。
不过,其他答案中提到了更为简洁的方法。您能解释/展示您的预期结果吗?[[3.5,1.0,0,4.0],[0,0,0],[3.0,1.0,0,-2.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)
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]]