如何从循环内正确修改python中循环的迭代器 [英] how to correctly modify the iterator of a loop in python from within the loop

查看:120
本文介绍了如何从循环内正确修改python中循环的迭代器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我基本上需要的是检查列表中的每个元素,如果某些条件适合我想从列表中删除它。

what I basically need is to check every element of a list and if some criteria fit I want to remove it from the list.

例如,让我们说

list=['a','b','c','d','e']

我基本上想写(原则上而不是我试图实现的实际代码)

I basically want to write (in principle and not the actual code I try to implement)

如果列表中的元素是'b'或'c',请将其从列表中删除,然后选择下一个。

If an element of the list is 'b' or 'c' remove it from the list and take the next.

for s in list:
    if s=='b' or s=='c':
        list.remove(s)

失败,因为当'b'被删除时,循环需要'd'而不是'c'作为下一个元素。那么有没有办法更快地将元素存储在单独的列表中并在之后删除它们?

fails because when 'b' is removed the loop takes 'd' and not 'c' as the next element. So is there a way to do that faster than storing the elements in a separate list and removing them afterwards?

谢谢。

推荐答案

更简单的方法是使用列表的副本 - 可以使用从列表的从开头延伸到结尾的切片来完成,例如这个:

The easier way is to use a copy of the list - it can be done with a slice that extends "from the beginning" to the "end" of the list, like this:

for s in list[:]:
    if s=='b' or s=='c':
        list.remove(s)

你考虑过这个,这是简单到你的代码,除非这个列表真的很大,并且在代码的关键部分(比如,在动作游戏的主循环中)。在这种情况下,我有时使用以下习语:

You have considered this, and this is simple enough to be in your code, unless this list is really big, and in a critical part of the code (like, in the main loop of an action game). In that case, I sometimes use the following idiom:

to_remove = []
for index, s in enumerate(list):
    if s == "b" or s == "c":
         to_remove.append(index)

for index in reversed(to_remove):
    del list[index]

当然你可以使用while循环:

Of course you can resort to a while loop instead:

index = 0
while index < len(list):
   if s == "b" or s == "c":
       del list[index]
       continue
   index += 1

这篇关于如何从循环内正确修改python中循环的迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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