惯用地否定过滤器
Idiomatically negate a filter
带否定的 filter
最惯用的写法是什么?
示例:
is_even= lambda x : x % 2 == 0
odd_numbers= filter( lambda x: not is_even(x), range(10) )
当然,您可以只使用列表推导式 - 但无论如何您都不需要使用 filter
如果有人想知道,我在尝试 split a list based on a condition
时偶然发现了这个
itertools
模块包括两个 ifilter() and ifilterfalse(),它们分别过滤函数 returns True
和 False
的元素。
odd_numbers = ifilterfalse(is_even, range(10))
请注意,在 Python 2 中,filter
和 ifilter
之间存在差异:odd_numbers
是一个迭代器,而 filter() 将给出列表(参见 itertools.ifilter Vs. filter Vs. list comprehensions). If you actually want to build a list, your example with not
seems fine, assuming you are set on using filter
- list comprehensions may be more 'idiomatic' (List filtering: list comprehension vs. lambda + filter)。
在Python3中,filter() constructs an iterator, not a list, and itertools.filterfalse()是补码。
基于谓词的拆分称为 partition
。我会发现将 partition
实现为一个单独的函数而不是专门针对奇数和偶数重复其内部结构更为惯用。 Python 3 的 Itertools Recipes 具有以下实现:
def partition(pred, iterable):
'Use a predicate to partition entries into false entries and true entries'
# partition(is_odd, range(10)) --> 0 2 4 6 8 and 1 3 5 7 9
t1, t2 = tee(iterable)
return filterfalse(pred, t1), filter(pred, t2)
它使用 filterfalse
(如@Lack 所述)和该模块中定义的 tee
。所以你的最高级别代码看起来像:
odds, evens = partition(is_even, range(10))
带否定的 filter
最惯用的写法是什么?
示例:
is_even= lambda x : x % 2 == 0
odd_numbers= filter( lambda x: not is_even(x), range(10) )
当然,您可以只使用列表推导式 - 但无论如何您都不需要使用 filter
如果有人想知道,我在尝试 split a list based on a condition
时偶然发现了这个itertools
模块包括两个 ifilter() and ifilterfalse(),它们分别过滤函数 returns True
和 False
的元素。
odd_numbers = ifilterfalse(is_even, range(10))
请注意,在 Python 2 中,filter
和 ifilter
之间存在差异:odd_numbers
是一个迭代器,而 filter() 将给出列表(参见 itertools.ifilter Vs. filter Vs. list comprehensions). If you actually want to build a list, your example with not
seems fine, assuming you are set on using filter
- list comprehensions may be more 'idiomatic' (List filtering: list comprehension vs. lambda + filter)。
在Python3中,filter() constructs an iterator, not a list, and itertools.filterfalse()是补码。
基于谓词的拆分称为 partition
。我会发现将 partition
实现为一个单独的函数而不是专门针对奇数和偶数重复其内部结构更为惯用。 Python 3 的 Itertools Recipes 具有以下实现:
def partition(pred, iterable):
'Use a predicate to partition entries into false entries and true entries'
# partition(is_odd, range(10)) --> 0 2 4 6 8 and 1 3 5 7 9
t1, t2 = tee(iterable)
return filterfalse(pred, t1), filter(pred, t2)
它使用 filterfalse
(如@Lack 所述)和该模块中定义的 tee
。所以你的最高级别代码看起来像:
odds, evens = partition(is_even, range(10))