Filter function:
The filter () function filters the sequence by using a custom function that filters a sequence, passes each item of the sequence to a custom filter function, and returns the result to be filtered. Finally, the filtered results are returned at once.
The filter () function has two parameters:
First, custom function name, required
The second, the column that needs to be filtered, is also necessary
The code is as follows |
Copy Code |
From random import Randint Allnums = [] For Eachnum in range (9): Allnums.append (Randint (1, 99)) Print filter (lambda n:n%2, allnums) |
Filter is to apply the front function to none of the elements, and then true to leave, false roll
The code is as follows |
Copy Code |
>>> map (Lambda x:x+2), [0, 1, 2, 3, 4, 5]) [2, 3, 4, 5, 6, 7] >>> >>> map (Lambda x:x**2, Range (6)) [0, 1, 4, 9, 16, 25] >>> [x+2 for X in range (6)] [2, 3, 4, 5, 6, 7] >>> >>>[x**2 for x in range (6)] [0, 1, 4, 9, 16, 25] |
The role of map is to apply a function to no elements, and to get a new array of new elements
The code is as follows |
Copy Code |
>>> print ' is: ', reduce (lambda x,y:x+y), Range (5)) The total is:10 Given the input above, the reduce () function runs the following arithmetic operations. ((((0 + 1) + 2) + 3) + 4 => 10 |
The effect of reduce is on top, come two get a new one, then the new element and the third one to handle ...
The code is as follows |
Copy Code |
# Coding=utf8
# defines a function greater than 5 less than 10 def guolvhanshu (num): If Num>5 and num<10: Return num
# define a sequence Seq= (12,50,8,17,65,14,9,6,14,5)
# using the filter function Result=filter (GUOLVHANSHU,SEQ)
# (8,9,6) Print result Execution results: (8, 9, 6) |
Because the 8,9,6 is more than 5, less than 10, so it's filtered down.
You can see the example:
The code is as follows |
Copy Code |
1 filter (function, sequence): str = [' A ', ' B ', ' C ', ' d '] def fun1 (s): return s if s!= ' a ' else None RET = filter (FUN1, str) Print ret # # [' B ', ' C ', ' d '] |
Performs a function (item) on the item in sequence, which makes a list/string/tuple (depending on the type of sequence) that executes the result to true.
Can be considered as a filter function.
For example, in a list, delete an even number and leave only the odd number, which can be written like this:
The code is as follows |
Copy Code |
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 in a sequence, you can write this:
The code is as follows |
Copy Code |
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.