- Learn Web Development with Python
- Fabrizio Romano Gaston C. Hillar Arun Ravindran
- 235字
- 2021-06-10 18:26:16
filter
According to the Python documentation:
Let's see a very quick example:
# filter.py
>>> test = [2, 5, 8, 0, 0, 1, 0]
>>> _(filter(None, test))
[2, 5, 8, 1]
>>> _(filter(lambda x: x, test)) # equivalent to previous one
[2, 5, 8, 1]
>>> _(filter(lambda x: x > 4, test)) # keep only items > 4
[5, 8]
In the preceding code, notice how the second call to filter is equivalent to the first one. If we pass a function that takes one argument and returns the argument itself, only those arguments that are True will make the function return True, therefore this behavior is exactly the same as passing None. It's often a very good exercise to mimic some of the built-in Python behaviors. When you succeed, you can say you fully understand how Python behaves in a specific situation.
Armed with map, zip, and filter (and several other functions from the Python standard library) we can massage sequences very effectively. But those functions are not the only way to do it. So let's see one of the nicest features of Python: comprehensions.