Python built-in functions (21) -- filter, pythonfilter
English document:
filter
(Function,Iterable)
Construct an iterator from those elementsIterableFor whichFunctionReturns true.IterableMay be either a sequence, a container which supports iteration, or an iterator. IfFunctionIsNone
, The identity function is assumed, that is, all elementsIterableThat are false are removed.
Note thatfilter(function, iterable)
Is equivalent to the generator expression(item for item in iterable if function(item))
If function is notNone
And(item for item in iterable if item)
If function isNone
.
Seeitertools.filterfalse()
For the complementary function that returns elementsIterableFor whichFunctionReturns false.
Note:
1. The filter function is used to filter sequences. The filtering method is to use the passed function to call the elements in the de-cyclic sequence. If the result of function compute is True, the elements are retained; otherwise, the elements are discarded.
>>> A = list (range () # define sequence >>> a [1, 2, 3, 4, 5, 6, 7, 8, 9] >>> def if_odd (x): # defines the return x % 2 = 1 >>> list (filter (if_odd, a) function of the odd number judgment )) # The odd numbers in the filter sequence [1, 3, 5, 7, 9]
2. When the function parameter is set to None, if the element value in the sequence is False, it is automatically discarded.
>>> C = ['', False, 'I', {}] # define sequence >>> c ['', False, 'I ', {}] >>> list (filter (None, c) # If the filter function is None, False values in the sequence are automatically discarded. All null strings, False values, and empty sequences are False values, so discard ['I']