The use of the filter () function in Python _python

Source: Internet
Author: User

The Python built-in filter () function is used to filter the sequence.

Like map (), filter () also receives a function and a sequence. When the map () is different, filter () acts on each element in turn, and then determines whether to retain or discard the element based on whether the return value is true or false.

For example, in a list, delete an even number and leave only the odd number, which can be written like this:

def is_odd (n): Return
  n% 2 = 1

filter (is_odd, [1, 2, 4, 5, 6, 9, ten])
# results: [1, 5, 9, 15]

To delete an empty string in a sequence, you can write this:

def not_empty (s): return
  S and S.strip ()

filter (Not_empty, [' A ', ', ', ' B ', None, ' C ', '])
# result: [' a ', ' B ', ' C ' ']

It is shown that the high order function with filter () is the key to implement a "filter" function correctly.
Practice

Try removing the prime number of the 1~100 with filter ().

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.