Python's built-in filter () function is used for filtering sequences.
Like map (), filter () also receives a function and a sequence. When different from map (), filter () applies the incoming function to each element sequentially, and then decides whether to persist or discard the element based on whether the return value is True or false .
For example, in a list, delete even numbers, keep only odd numbers, and you can write:
def is_odd (n):
return n% 2 = = 1
Filter (is_odd, [1, 2, 4, 5, 6, 9, 10, 15])
# results: [1, 5, 9, 15]
To delete an empty string from a sequence, you can write:
def not_empty (s):
return s and S.strip ()
Filter (Not_empty, [' A ', ' ', ' B ', None, ' C ', '])
# result: [' A ', ' B ', ' C ']
The key is to implement a "filter" function correctly by using the filter () as a high-order function.
Def f1 (a): if a = = 3: pass else: return a*ali = [1,2,3,4]for i in Filter (F1,li): print (i)
Filter ()