Python built-in functions (21) -- filter, pythonfilter

Source: Internet
Author: User

Python built-in functions (21) -- filter, pythonfilter

English document:

filter(Function,Iterable)

Construct an iterator from those elementsIterableFor whichFunctionReturns true.IterableMay be either a sequence, a container which supports iteration, or an iterator. IfFunctionIsNone, The identity function is assumed, that is, all elementsIterableThat are false are removed.

Note thatfilter(function, iterable)Is equivalent to the generator expression(item for item in iterable if function(item))If function is notNoneAnd(item for item in iterable if item)If function isNone.

Seeitertools.filterfalse()For the complementary function that returns elementsIterableFor whichFunctionReturns false.

 

Note:

1. The filter function is used to filter sequences. The filtering method is to use the passed function to call the elements in the de-cyclic sequence. If the result of function compute is True, the elements are retained; otherwise, the elements are discarded.

>>> A = list (range () # define sequence >>> a [1, 2, 3, 4, 5, 6, 7, 8, 9] >>> def if_odd (x): # defines the return x % 2 = 1 >>> list (filter (if_odd, a) function of the odd number judgment )) # The odd numbers in the filter sequence [1, 3, 5, 7, 9]

2. When the function parameter is set to None, if the element value in the sequence is False, it is automatically discarded.

>>> C = ['', False, 'I', {}] # define sequence >>> c ['', False, 'I ', {}] >>> list (filter (None, c) # If the filter function is None, False values in the sequence are automatically discarded. All null strings, False values, and empty sequences are False values, so discard ['I']

 

Related Article

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.