Filter, lambda function expression

Source: Internet
Author: User
Python basic filter, lambda function expression filter (function or None, sequence), where sequence can be list, tuple, string. This function filters out all elements in the sequence that return True or bool (return value) as True when calling the function using the element itself as a parameter and returns the result in a list. the filter can only accept two parameters (function, sequence), and only one value can be returned in the function.

First, a simple code:

print max(filter(lambda x: 555555 % x == 0, range(100, 999)))

The code indicates the approximate number of the three-digit maximum output of 555555.

First, the first knowledge point of this code is the built-in function filter of python.

The filter () function is used to filter the list. The simplest statement is to use a function to filter a list and pass each item of the list to the filter function. if the filter function returns false, the item is deleted from the list.

The filter () function includes two parameters: function and list. This function filters out items in the list parameter based on whether the results returned by the function parameter are true, and returns a new list.

Simply put, the filter () function is equivalent to the following code:

c = [b for b in a1 if b > 2]print c

The second knowledge point is the lambda () function.

Python supports this syntax, which allows you to quickly define the smallest functions of a single row. these functions, called lambda, are borrowed from Lisp.

def f(x):    return x * 2g = lambda x: x * 2(lambda x: x * 2)(3)

According to the code, the lambda function completes the same thing as a normal function, and lambda does not have parentheses around the parameter list, and ignores the return keyword (the return implicit exists, because the function has only one row and the function has no name, you can assign it to a variable for calling)

The last code section shows that a lambda function is just an inline function.

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.