The filter () function is another useful high-order function built into Python, and the filter () function receives a function f and a list, the function F of which is to judge each element, returning True or False,filter () Automatically filters out non-conforming elements based on the result of the decision, returning a new list of eligible elements.
For example, to delete an even number from a list [1, 4, 6, 7, 9, 12, 17] and keep an odd number, first, write a function that judges the odd number:
def is_odd (x): return x% 2 = = 1
Then, filter out the even number using filter ():
>>>filter (Is_odd, [1, 4, 6, 7, 9, 12, 17])
Results:
[1, 7, 9, 17]
With filter (), you can accomplish many useful functions, such as deleting None or an empty string:
def is_not_empty (s): return S and Len (S.strip ()) > 0>>>filter (is_not_empty, [' Test ', None, ' ', ' str ', '
', ' END '])
Results:
[' Test ', ' str ', ' END ']
Note: S.strip (RM) Deletes the characters of the RM sequence at the beginning and end of the S string.
When RM is empty, the default is to remove the white space character (including ' \ n ', ' \ R ', ' \ t ', '), as follows:
>>> a = ' 123 '
>>> A.strip ()
' 123 '
>>> a = ' \t\t123\r\n '
>>> A.strip ()
' 123 '
Practice:
Filter () to 1~100 that the square root is an integer number, i.e. the result should be:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Method:
Import Mathdef IS_SQR (x): return math.sqrt (x)% 1 = = 0print Filter (IS_SQR, Range (1, 101))
Results:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
The filter function in Python