Python basic Tutorial: How to Use Filter, pythonfilter

Source: Internet
Author: User

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!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.