遍历列表和删除python中的元素时的奇怪行为 [英] Weird behaviour when iterating through list and deleting elements in python

查看:76
本文介绍了遍历列表和删除python中的元素时的奇怪行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试遍历Python列表,并在完成一些任务后删除每个元素,但是每次迭代后它都会跳一个元素,我不知道为什么:

I'm trying to iterate over a Python list and delete each element once I've done some tasks with it, but it jumps one element after each iteration and I don't know why:

>>> simple_list = list(range(10))
>>> simple_list
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]


>>> for i in simple_list:
...     print(i)
...     simple_list.remove(i)
... 
0
2
4
6
8

>>> simple_list
[1, 3, 5, 7, 9]

有人知道为什么会这样吗?只有偶数元素被删除,并且看起来循环并没有穿过不均匀的元素.

Does anyone know why this is happening? Only the even elements are being removed, and looks like the loop doesn't go through the uneven ones.

推荐答案

好吧,当您遍历列表时,列表正在缩小.如果需要的话,只需遍历第一个元素即可.

Well, your list is shrinking while you are iterating over it. If you want to, just look at the first element while your iterate over it.

while len(simple_list) > 0:
    print(simple_list[0])
    del simple_list[0]

这篇关于遍历列表和删除python中的元素时的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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