Using the filter() function to pass or reject data
The job of the
filter()
function is to use and apply a decision function called a predicate to each value in a collection. A decision of True
means that the value is passed; otherwise, the value is rejected. The itertools
module includes filterfalse()
as variations on this theme. Refer to Chapter 8, The Itertools Module to understand the usage of the itertools
module's filterfalse()
function.
We might apply this to our trip data to create a subset of legs that are over 50 nautical miles long, as follows:
long= list(filter(lambda leg: dist(leg) >= 50, trip)))
The predicate lambda
will be True
for long legs, which will be passed. Short legs will be rejected. The output is the 14 legs that pass this distance test.
This kind of processing clearly segregates the filter rule (lambda leg: dist(leg) >= 50
) from any other processing that creates the trip
object or analyzes the long legs.
For another simple example, look at the following code...