Python basic Tutorial: How to Use Filter, pythonfilter
Python Filter
The built-in function filter () in Python is mainly used to filter sequences.
Similar to map, filter () also receives a function and a sequence. Unlike map (), filter () applies the input function to each element in sequence, and then
True or False determine whether to retain or discard the element.
Example 1:
Number_list = range (-5, 5) less_than_zero = list (filter (lambda x: x <0, number_list) print (less_than_zero)
The output result of the above example is:
[-5,-4,-3,-2,-1]
Example 2: in a list, delete the even number and only keep the odd number. You can write it as follows:
Def is_odd (n): return n % 2 = 1 list (filter (is_odd, [1, 2, 4, 5, 6, 9, 10, 15])
The output result of the program change is:
[1, 5, 9, 15]
Note: The filter () function returns an Iterator, that is, an Iterator. To force the filter () to complete the calculation result, you must use the list () function to obtain all the results and return the list.
Thank you for reading this article. I hope it will help you. Thank you for your support for this site!