Home > Article > Backend Development > python basic tutorial how to use Filter
python Filter
#The built-in function filter() in Python is mainly used to filter sequences.
Similar to map, filter() also receives a function and sequence. Unlike map(), filter() applies the passed function to each element in turn, and then based on the return value Whether
True or False determines whether to keep 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 of the above example is:
[-5, -4, -3, -2, -1]
Example 2: In a list, delete even numbers and keep only odd numbers. You can write like this:
def is_odd(n): return n % 2 == 1 list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15]))
Change the program output result to:
[1, 5, 9, 15]
Note: the filter() function returns an Iterator, which is an iterator , so to force filter() to complete the calculation results, you need to use the list() function to obtain all results and return the list.
Thank you for reading, I hope it can help you, thank you for your support of this site!
For more articles related to the basic python tutorial on how to use Filter, please pay attention to the PHP Chinese website!