Home > Backend Development > Python Tutorial > python basic tutorial how to use Filter

python basic tutorial how to use Filter

高洛峰
Release: 2017-02-21 10:43:06
Original
1626 people have browsed it

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)
Copy after login

The output of the above example is:

[-5, -4, -3, -2, -1]
Copy after login

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]))
Copy after login

Change the program output result to:

[1, 5, 9, 15]
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template