Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在python中重写嵌套列表中某个元素的值?_Python_List_Indexing_Nested_Rewrite - Fatal编程技术网

如何在python中重写嵌套列表中某个元素的值?

如何在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。但它显示了一个错误:

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]]