Elegant way to remove items from sequence in Pytho

2020-01-29 03:23发布

When I am writing code in Python, I often need to remove items from a list or other sequence type based on some criteria. I haven't found a solution that is elegant and efficient, as removing items from a list you are currently iterating through is bad. For example, you can't do this:

for name in names:
    if name[-5:] == 'Smith':
        names.remove(name)

I usually end up doing something like this:

toremove = []
for name in names:
    if name[-5:] == 'Smith':
        toremove.append(name)
for name in toremove:
    names.remove(name)
del toremove

This is innefficient, fairly ugly and possibly buggy (how does it handle multiple 'John Smith' entries?). Does anyone have a more elegant solution, or at least a more efficient one?

How about one that works with dictionaries?

14条回答
Luminary・发光体
2楼-- · 2020-01-29 04:23
names = filter(lambda x: x[-5:] != "Smith", names);
查看更多
孤傲高冷的网名
3楼-- · 2020-01-29 04:24

You can also iterate backwards over the list:

for name in reversed(names):
    if name[-5:] == 'Smith':
        names.remove(name)

This has the advantage that it does not create a new list (like filter or a list comprehension) and uses an iterator instead of a list copy (like [:]).

Note that although removing elements while iterating backwards is safe, inserting them is somewhat trickier.

查看更多
登录 后发表回答