由于list.pop()调用,“ For”索引发生了变化

我有这个Python代码,它面对一个整数列表中的项目(在发布的代码中命名为“ seen”)与所有其他列表的.f字段中的所有项目(在发布的代码中命名为“ maxx”) )。


在每次迭代中,我都在(通过c变量)计算第j个项目出现在“ maxx”列表中的次数,pop()如果它少于3次,我希望从列表中进行选择。


该代码可以正常工作,但是弹出一个项目会将“可见”列表中的任何后续项目“拉回”一个位置,因此,每次满足条件时,循环都会错过列表中的下一个项目。


这是代码:


for indj,j in enumerate(seen):    # every item in the 'seen' list..

    c=0

    for k in maxx:                # ..checks for a matching item in the 'maxx' list

        if j==k.f:

            c=c+1;

    if c<3:                       # if the item appears less than 3 times we pop it

        seen.pop(indj)

我尝试添加:


indj=indj-1

j=seen[indj]

在if构建的最后,但是没有用


qq_花开花谢_0
浏览 294回答 2
2回答

慕田峪9158850

您必须制作一个新列表或使用一个副本。当您在循环浏览时更改列表时,将跳过某些项目。我会这样做:def filter_low(lst, maxk, threshold=3):&nbsp; &nbsp; for item in lst:&nbsp; &nbsp; &nbsp; &nbsp; c = sum(1 for k in maxx if item==k.f)&nbsp; &nbsp; &nbsp; &nbsp; if c >= threshold:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;yield itemnew_seen = list(filter_low(seen, maxk, 3))与以下内容相同:new_seen = [item for item in seen&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if sum(1 for k in maxx if item==k.f) >= 3]您可以通过以下方式更改原始列表seen[:] = [item for item in seen&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if sum(1 for k in maxx if item==k.f) >= 3]

茅侃侃

修改要迭代的列表绝不是一个好主意。您可以遍历一个副本并使用以下命令修改实际列表popped = 0for indj, j in enumerate(seen[:]):&nbsp;&nbsp;&nbsp; &nbsp; s = sum(j == k.f for k in maxx)&nbsp; &nbsp; if s < 3:&nbsp; &nbsp; &nbsp; &nbsp; seen.pop(indj - popped)&nbsp; &nbsp; &nbsp; &nbsp; popped += 1如果seen列表很大,可能效率不高。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python