从列表中删除项目时出现奇怪的结果 [英] strange result when removing item from a list

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

问题描述

我有这段代码:

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]

[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, I'm assuming 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之前对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天全站免登陆