The filter function in Python

Source: Internet
Author: User
Tags square root

The filter () function is another useful high-order function built into Python, and the filter () function receives a function f and a list, the function F of which is to judge each element, returning True or False,filter () Automatically filters out non-conforming elements based on the result of the decision, returning a new list of eligible elements.

For example, to delete an even number from a list [1, 4, 6, 7, 9, 12, 17] and keep an odd number, first, write a function that judges the odd number:

def is_odd (x):    return x% 2 = = 1

Then, filter out the even number using filter ():

>>>filter (Is_odd, [1, 4, 6, 7, 9, 12, 17])

Results:

[1, 7, 9, 17]

With filter (), you can accomplish many useful functions, such as deleting None or an empty string:

def is_not_empty (s):    return S and Len (S.strip ()) > 0>>>filter (is_not_empty, [' Test ', None, ' ', ' str ', ' 
    ', ' END '])

Results:

[' Test ', ' str ', ' END ']

Note: S.strip (RM) Deletes the characters of the RM sequence at the beginning and end of the S string.

When RM is empty, the default is to remove the white space character (including ' \ n ', ' \ R ', ' \ t ', '), as follows:

>>> a = ' 123 '
>>> A.strip ()
' 123 '

>>> a = ' \t\t123\r\n '
>>> A.strip ()
' 123 '

Practice:

Filter () to 1~100 that the square root is an integer number, i.e. the result should be:

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Method:

Import Mathdef IS_SQR (x):    return math.sqrt (x)% 1 = = 0print Filter (IS_SQR, Range (1, 101))

Results:

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

The filter function in Python

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.