一种可能性是使用filter:
>>> import operator
>>> import functools
>>> suits = ["h", "c", "d", "s"]
>>> # Python 3.x
>>> list(filter(functools.partial(operator.ne, 'c'), suits))
['h', 'd', 's']
>>> # Python 2.x
>>> filter(functools.partial(operator.ne, 'c'), suits)
['h', 'd', 's']
这里也可以使用'c' 的__ne__ 方法来代替partial:
>>> list(filter('c'.__ne__, suits))
['h', 'd', 's']
但是,后一种方法被认为不是非常 Pythonic(通常您不应该直接使用特殊方法 - 以双下划线开头),如果列表包含混合类型,它可能会给出奇怪的结果,但它可能比partial 方法快一点。
suits = ["h", "c", "d", "s"]*200 # more elements for more stable timings
%timeit list(filter('c'.__ne__, suits))
# 164 µs ± 5.98 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
%timeit list(filter(functools.partial(operator.ne, 'c'), suits))
# 337 µs ± 13.3 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
%timeit list(filter(lambda x: x != 'c', suits))
# 410 µs ± 13.7 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
%timeit [x for x in suits if x != "c"]
181 µs ± 465 ns per loop (mean ± std. dev. of 7 runs, 1000 loops each)
Python 3.5.2 使用 IPython 的魔法 %timeit 命令测试。