Idiomatically negate filter

What is the most idiomatic way to write a filter with negation?

Example:

 is_even= lambda x : x % 2 == 0 odd_numbers= filter( lambda x: not is_even(x), range(10) ) 

Of course you can just use lists, but then you don't need to use filter anyway

If someone is wondering, I stumbled upon this while trying to split a list based on a condition

+5
source share
2 answers

The itertools module includes ifilter () and ifilterfalse () , which filter elements in which the function returns True and False respectively.

 odd_numbers = ifilterfalse(is_even, range(10)) 

Note that in Python 2 there is a difference between filter and ifilter : odd_numbers will be an iterator here, while filter () will provide a list (see itertools.ifilter Vs. filter Vs. list comprehensions ). If you really want to create a list, your example with not seems fine, if you are configured to use filter - lists can be more "idiomatic" ( Filtering lists: list compared to lambda + filter ).

In Python 3, filter () builds an iterator, not a list, and itertools.filterfalse () is a complement.

+5
source

The predicate-based partition is called partition . It would be more idiomatic for me to implement partition as a separate function, rather than repeating its insides specifically for odd and even numbers. Python 3 Recipes Itertools has the following implementation:

 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) 

It uses filterfalse (as described in @Lack) and tee defined in this module. So your top-level code will look like this:

 odds, evens = partition(is_even, range(10)) 
+1
source

Source: https://habr.com/ru/post/1210756/


All Articles