Python:在遍历列表时删除列表元素 [英] Python: Removing list element while iterating over list

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

问题描述

我正在遍历Python中的元素列表,对其进行一些操作,然后在满足特定条件的情况下将其删除.

I'm iterating over a list of elements in Python, do some action on it, and then remove them if they meet certain criteria.

for element in somelist:
    do_action(element)
    if check(element):
        remove_element_from_list

我应该使用什么来代替remove_element? 我曾问过类似的问题,但注意到将要对所有元素执行的do_action部分的存在,因此消除了使用过滤器的解决方案.

What should I use in place of remove_element? I have seen similar questions asked, but notice the presence of the do_action part that is to be executed for all elements and thus eliminates the solution of using filters.

推荐答案

您始终可以遍历列表的副本,从而可以自由修改原始列表:

You could always iterate over a copy of the list, leaving you free to modify the original:

for item in list(somelist):
  ...
  somelist.remove(item)

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

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