循环在遍历整个列表之前停止

时间:2020-04-26 20:23:06

标签: python list loops

我试图删除res [1]中所有小于120的值,并删除res [0]中相同索引的值,由于某种原因,循环停止了..并且不继续删除结尾的列表。

非常感谢您的支持

代码如下:

def func ():
    res=([30.0,40.0,49.0,28.0,30.0,57.0], [0, 30.0,400.0,160.0, 30.0, 30.0])
    for i in res[1]:
        if i<120:
            ind=res[1].index(i)
            res[1].remove(i)
            del(res[0][ind])
        else:
            pass

    return res 

预期结果是([49.0, 28.0], [400.0, 160.0]),但我有这个结果([49.0, 28.0, 30.0, 57.0], [400.0, 160.0, 30.0, 30.0])

4 个答案:

答案 0 :(得分:2)

检查i < 120而不是检查i >= 120,只需将通过的项目添加到新列表中,然后将包含这些列表的元组返回。

In [179]: def func(): 
     ...:     res=([30.0,40.0,49.0,28.0,30.0,57.0], [0, 30.0,400.0,160.0, 30.0, 30.0]) 
     ...:     r0, r1 = [], [] 
     ...:     for i in res[1]: 
     ...:         if i >= 120: 
     ...:             ind=res[1].index(i) 
     ...:             r1.append(i) 
     ...:             r0.append(res[0][ind])
     ...:     return (r0, r1) 
     ...:      

In [180]: func()
Out[180]: ([49.0, 28.0], [400.0, 160.0])

答案 1 :(得分:1)

尝试一下:

def func():
    res=([30.0,40.0,49.0,28.0,30.0,57.0], [0, 30.0,400.0,160.0, 30.0, 30.0])
    indices = [i for i,j in enumerate(res[1]) if j<120]
    res1 = [i for i in res[1] if i<120]
    res0 = [j for i,j in enumerate(res[0]) if i not in indices]
    result = (res0, res1)
    return result

对元组的第二项进行浅表复制,然后在其上循环。您的代码中需要修改:

def func ():
    res=([30.0,40.0,49.0,28.0,30.0,57.0], [0, 30.0,400.0,160.0, 30.0, 30.0])
    res1 = res[1][:]
    for i in res1:
        if i<120:
            ind=res1.index(i)
            res1.remove(i)
            del(res[0][ind])
        else:
            pass
    res = (res[0], res1)
    return res 

答案 2 :(得分:1)

您正在修改要迭代的列表,这不是愚蠢的做法。 使用

for i in res[1][:]:

这将导致创建新的迭代列表

答案 3 :(得分:1)

这实际上是How to remove items from a list while iterating?的副本,但是该问题中的代码仅涉及一个列表,而不涉及两个。

只需复制res[1]并对其进行迭代:

res = ([30.0, 40.0, 49.0, 28.0, 30.0, 57.0], [0, 30.0, 400.0, 160.0, 30.0, 30.0])
for i in res[1].copy():  # <- Here
    if i < 120:
        ind = res[1].index(i)
        del res[1][ind]
        del res[0][ind]
print(res)  # -> ([49.0, 28.0], [400.0, 160.0])

BTW del是一个语句,而不是一个函数,因此不带括号的参数会更清楚。


尽管恕我直言,res[1].index(i)有点麻烦,因为您已经在进行迭代,所以我想出了这个功能性解决方案,它严重依赖于zip

pairs = (t for t in zip(*res) if t[1] >= 120)
res = tuple(map(list, zip(*pairs)))  # Cast to tuple of lists

还有一个从Mayank's answer借用但使用zip的解决方案:

r0, r1 = [], []
for x, y in zip(*res):
    if y >= 120:
        r0.append(x)
        r1.append(y)
res = r0, r1
相关问题