Home  >  Article  >  Backend Development  >  python basic tutorial how to use Filter

python basic tutorial how to use Filter

高洛峰
高洛峰Original
2017-02-21 10:43:061574browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn