How to remove items from a list while iterating?

2020-01-22 09:57发布

I'm iterating over a list of tuples in Python, and am attempting to remove them if they meet certain criteria.

for tup in somelist:
    if determine(tup):
         code_to_remove_tup

What should I use in place of code_to_remove_tup? I can't figure out how to remove the item in this fashion.

26条回答
做个烂人
2楼-- · 2020-01-22 10:55

You might want to use filter() available as the built-in.

For more details check here

查看更多
迷人小祖宗
3楼-- · 2020-01-22 10:55

Most of the answers here want you to create a copy of the list. I had a use case where the list was quite long (110K items) and it was smarter to keep reducing the list instead.

First of all you'll need to replace foreach loop with while loop,

i = 0
while i < len(somelist):
    if determine(somelist[i]):
         del somelist[i]
    else:
        i += 1

The value of i is not changed in the if block because you'll want to get value of the new item FROM THE SAME INDEX, once the old item is deleted.

查看更多
登录 后发表回答