The filter function is a Python built-in function, used to filter the sequence, filter out the elements that do not meet the conditions, and return an iterator object
filter(function, iterable)
- function - judgment function.
- iterable-iterable object.
If function returns True, add the current value to the new iterable object
Example: a list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], we want to get all odd elements in the list
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
def is_odd(n):
if n % 2 != 0:
return True
return False
new_list = filter(is_odd, a)
# new_list是一个可以迭代的对象
for i in new_list:
print(i)
The results are as follows: