The Python built-in filter () function is used to filter the sequence.
Like map (), filter () also receives a function and a sequence. When the map () is different, filter () acts on each element in turn, and then determines whether to retain or discard the element based on whether the return value is true or false.
For example, in a list, delete an even number and leave only the odd number, which can be written like this:
def is_odd (n): Return
n% 2 = 1
filter (is_odd, [1, 2, 4, 5, 6, 9, ten])
# results: [1, 5, 9, 15]
To delete an empty string in a sequence, you can write this:
def not_empty (s): return
S and S.strip ()
filter (Not_empty, [' A ', ', ', ' B ', None, ' C ', '])
# result: [' a ', ' B ', ' C ' ']
It is shown that the high order function with filter () is the key to implement a "filter" function correctly.
Practice
Try removing the prime number of the 1~100 with filter ().