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 ()) > 0filter (is_not_empty, [' Test ', None, ' ', ' str ', ' ' , ' END '])
Result: [' 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 ()
Result: ' 123 '
A= ' \t\t123\r\n ' A.strip ()
Result: ' 123 '
Task
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]
-
? What's going on?
-
The function that the filter () receives must determine whether the square root of a number is an integer, and math.sqrt () returns the result as a floating point.
Reference code:
Import Mathdef IS_SQR (x): r = Int (math.sqrt (x)) return r*r==xprint filter (IS_SQR, Range (1, 101))
Python's filter () function