1)近乎英式风格:
使用以下命令测试存在性in
运算符,然后应用remove
method.
if thing in some_list: some_list.remove(thing)
The remove
方法将仅删除第一次出现的thing
,为了删除所有出现的情况,您可以使用while
代替if
.
while thing in some_list: some_list.remove(thing)
- 足够简单,可能是我的选择。对于小列表(无法抗拒俏皮话)
2) 鸭型 http://docs.python.org/glossary.html#term-duck-typing, EAFP http://docs.python.org/glossary.html#term-eafp style:
这种先拍后问的态度在 Python 中很常见。无需提前测试对象是否合适,只需执行操作并捕获相关异常即可:
try:
some_list.remove(thing)
except ValueError:
pass # or scream: thing not in some_list!
except AttributeError:
call_security("some_list not quacking like a list!")
当然,上面例子中的第二个 except 子句不仅是有问题的幽默,而且完全没有必要(重点是向不熟悉这个概念的人说明鸭子类型)。
如果您预计事情会多次出现:
while True:
try:
some_list.remove(thing)
except ValueError:
break
- 对于这个特定的用例来说有点冗长,但在 Python 中非常惯用。
- 这比#1 表现更好
-
PEP 463 http://www.python.org/dev/peps/pep-0463/提出了一种更短的 try/ except 简单用法语法,这在这里会很方便,但没有被批准。
然而,随着contextlib的suppress()上下文管理器 https://docs.python.org/3/library/contextlib.html#contextlib.suppress(python 3.4中引入)上面的代码可以简化为:
with suppress(ValueError, AttributeError):
some_list.remove(thing)
同样,如果您预计事情会多次出现:
with suppress(ValueError):
while True:
some_list.remove(thing)
3)功能风格:
1993 年左右,Python 得到了lambda
, reduce()
, filter()
and map()
,由Lisp https://en.wikipedia.org/wiki/Lisp_%28programming_language%29错过了它们并提交了工作补丁的黑客*。您可以使用filter
从列表中删除元素:
is_not_thing = lambda x: x is not thing
cleaned_list = filter(is_not_thing, some_list)
有一个快捷方式可能对您的情况有用:如果您想过滤掉空项目(实际上是其中的项目)bool(item) == False
, like None
、零、空字符串或其他空集合),您可以传递 None 作为第一个参数:
cleaned_list = filter(None, some_list)
-
[update]:在Python 2.x中,
filter(function, iterable)
曾经相当于[item for item in iterable if function(item)]
(or [item for item in iterable if item]
如果第一个参数是None
);在 Python 3.x 中,它现在相当于(item for item in iterable if function(item))
。细微的区别是过滤器过去用于返回列表,现在它的工作方式类似于生成器表达式 - 如果您只是迭代清理后的列表并丢弃它,这是可以的,但如果您确实需要一个列表,则必须将filter()
打电话给list()
构造函数。
- *这些 Lispy 风格的结构在 Python 中被认为有点陌生。 2005年左右,吉多甚至谈到了放弃filter http://www.artima.com/weblogs/viewpost.jsp?thread=98196- 与同伴一起
map
and reduce
(他们还没有消失,但是reduce
被搬进了功能工具 http://docs.python.org/2/library/functools.html#functools.reduce模块,如果你喜欢的话值得一看高阶函数 http://en.wikipedia.org/wiki/Higher-order_function).
4)数学风格:
列表推导式 http://en.wikipedia.org/wiki/List_comprehension自 2.0 版本引入以来,成为 Python 中列表操作的首选样式PEP 202 http://www.python.org/dev/peps/pep-0202/。其背后的基本原理是列表推导式提供了一种更简洁的方法来在以下情况下创建列表:map()
and filter()
和/或当前将使用嵌套循环。
cleaned_list = [ x for x in some_list if x is not thing ]
生成器表达式是在 2.4 版本中引入的PEP 289 http://www.python.org/dev/peps/pep-0289/。生成器表达式更适合您实际上不需要(或想要)在内存中创建完整列表的情况 - 例如当您只想一次迭代一个元素时。如果您仅迭代列表,则可以将生成器表达式视为惰性评估 http://en.wikipedia.org/wiki/Lazy_evaluation列表理解:
for item in (x for x in some_list if x is not thing):
do_your_thing_with(item)
- See 这个 Python 历史博客 http://python-history.blogspot.com.br/2010/06/from-list-comprehensions-to-generator.html发帖者GvR http://en.wikipedia.org/wiki/Guido_van_Rossum.
- 这个语法的灵感来自于集合构建器符号 http://en.wikipedia.org/wiki/Set-builder_notation在数学中。
- Python 3 也有set http://www.python.org/dev/peps/pep-3100/#id103 and 字典理解 http://www.python.org/dev/peps/pep-0274/.
Notes
- 您可能想使用不等式运算符
!=
代替is not
(差异很重要 https://stackoverflow.com/q/2209755/)
- 对于暗示列表副本的方法的批评者:与流行的看法相反,生成器表达式并不总是比列表理解更有效 - 请在抱怨之前进行分析