在Python中从序列中删除项目的优雅方法? [英] Elegant way to remove items from sequence in Python?

查看:111
本文介绍了在Python中从序列中删除项目的优雅方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我用Python编写代码时,经常需要根据某些条件从列表或其他序列类型中删除项目.我还没有找到一种既优雅又高效的解决方案,因为从当前正在迭代的列表中删除项目是很糟糕的.例如,您不能执行以下操作:

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?

使用字典的情况如何?

推荐答案

仅完成过滤的两种简单方法是:

Two easy ways to accomplish just the filtering are:

  1. 使用filter:

names = filter(lambda name: name[-5:] != "Smith", names)

使用列表理解:

names = [name for name in names if name[-5:] != "Smith"]

请注意,这两种情况都将谓词函数求值的值保留为True,因此您必须颠倒逻辑(即,说保持姓氏为史密斯的人"而不是删除姓氏为史密斯的人").姓史密斯的人").

Note that both cases keep the values for which the predicate function evaluates to True, so you have to reverse the logic (i.e. you say "keep the people who do not have the last name Smith" instead of "remove the people who have the last name Smith").

编辑有趣的是……两个人分别发布了我在发布我的建议时提出的两个答案.

Edit Funny... two people individually posted both of the answers I suggested as I was posting mine.

这篇关于在Python中从序列中删除项目的优雅方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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