首页 > 解决方案 > 基于集合成员的过滤

问题描述

我会喜欢

small_evens = set([2, 4, 6, 8])
only_small_odds = filter(not in small_evens, [1, 3, 4, 1, 1, 2, 7, 6, 4, 5])

但当然这是一个语法错误。

两者都filter(lambda x: x not in set, items)觉得[x for x in items if x not in set]太冗长了。

还有其他方法吗?

我怀疑可能是因为,例如,较新的 Python 版本已经成为map(str.lower, strings)可能(过去必须map(lambda s: s.lower(), strings)

标签: pythonpython-3.x

解决方案


你可以这样做,这非常接近:

from itertools import filterfalse

only_small_odds = filterfalse(small_evens.__contains__, [1, 3, 4, 1, 1, 2, 7, 6, 4, 5])

推荐阅读