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)