Filter, lambda function expression

Source: Internet
Author: User
Filter (function or None, sequence), where sequence can be list, tuple,string. The function is to filter out all elements in sequence that return TRUE or bool (return value) to true when calling function as parameters, and return as a list. Filter can only accept two parameters (Function,sequence), where only one value can be returned in function functions

Let's start with a simple code:

Print Max (filter (lambda x:555555% x = = 0, range (100, 999)))

The code means the approximate number of the maximum three digits of the output 555555.

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

The filter () function is used to filter the list. The simplest argument is to use a function to filter a list, pass each item of the list into the filter function, and the filter function to return False to remove the item from the list.

The filter () function consists of two parameters, function, and list. That is, the function filters the items in the list parameter based on whether the result returned by the functions parameter is true, and finally returns a new list.

In simple terms, the filter () function is equivalent to the following code:

c = [B for b in A1 if B > 2]print c

The second point of knowledge is the lambda () function

Python supports this syntax, which allows the user to quickly define the minimum functions of a single line, which are called lambda functions borrowed from Lisp.

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

As you can see from the code, the lambda function accomplishes the same thing as the normal function, and the lambda has no parentheses around the argument list, and the return keyword is omitted (the return implied exists because the whole function has only one row and the function has no name. But it can be assigned to a variable to invoke)

The last piece of code shows that the lambda function is just an inline function.

  • 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.