The Python filter of filters a sequence instance using a custom function
- 2020-04-02 14:00:16
- OfStack
The filter function:
The filter() function filters a sequence, meaning that you can use a custom function to filter a sequence, pass each item of the sequence to a custom filter, and return the result to filter. The filtered result is returned once.
The filter() function takes two arguments:
The first one, the name of the custom function, is required
Second, columns that need to be filtered are also required
The DEMO
Demand, filter the number greater than 5 and less than 10:
# coding=utf8
# Definition is greater than the 5 Less than 10 The function of
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)
# use filter function
result=filter(guolvhanshu,seq)
# (8,9,6)
print result
Execution results:
(8, 9, 6)
Because 8,9,6 is greater than 5 and less than 10 so it's filtered out.