在列表上进行迭代时从列表中删除项目时,结果奇怪 [英] Strange result when removing item from a list while iterating over it

查看:54
本文介绍了在列表上进行迭代时从列表中删除项目时,结果奇怪的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这段代码:

numbers = range(1, 50)

for i in numbers:
    if i < 20:
        numbers.remove(i)

print(numbers)

但是我得到的结果是:
[2、4、6、8、10、12、14、16、18、20、21、22、23、24、25、26、27、28、29、30、31、32、33,34、35、36、37、38、39、40、41、42、43、44、45、46、47、48、49]

but the result I'm getting is:
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]

当然,我希望低于20的数字不会出现在结果中.看起来我在执行删除操作时出了问题.

Of course, I'm expecting the numbers below 20 to not appear in the results. Looks like I'm doing something wrong with the remove.

推荐答案

在迭代列表时,您正在修改列表.这意味着第一次通过循环 i == 1 ,因此将1从列表中删除.然后, for 循环转到列表中的第二项,它不是2,而是3!然后将其从列表中删除,然后 for 循环继续到列表中的第三项,现在为5.依此类推.用^指向 i 的值,也许像这样更容易可视化:

You're modifying the list while you iterate over it. That means that the first time through the loop, i == 1, so 1 is removed from the list. Then the for loop goes to the second item in the list, which is not 2, but 3! Then that's removed from the list, and then the for loop goes on to the third item in the list, which is now 5. And so on. Perhaps it's easier to visualize like so, with a ^ pointing to the value of i:

[1, 2, 3, 4, 5, 6...]
 ^

最初是列表的状态;然后删除1,然后循环转到列表中的第二项:

That's the state of the list initially; then 1 is removed and the loop goes to the second item in the list:

[2, 3, 4, 5, 6...]
    ^
[2, 4, 5, 6...]
       ^

以此类推.

没有一种好的方法可以在迭代列表时更改列表的长度.您能做的最好的事情是这样的:

There's no good way to alter a list's length while iterating over it. The best you can do is something like this:

numbers = [n for n in numbers if n >= 20]

或对此进行就地更改(parens中的内容是生成器表达式,在切片分配之前隐式转换为元组):

or this, for in-place alteration (the thing in parens is a generator expression, which is implicitly converted into a tuple before slice-assignment):

numbers[:] = (n for in in numbers if n >= 20)

如果你想在删除之前对 n 执行一个操作,你可以尝试的一个技巧是:

If you want to perform an operation on n before removing it, one trick you could try is this:

for i, n in enumerate(numbers):
    if n < 20 :
        print("do something")
        numbers[i] = None
numbers = [n for n in numbers if n is not None]

这篇关于在列表上进行迭代时从列表中删除项目时,结果奇怪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆