Home  >  Article  >  Backend Development  >  filter, lambda function expression

filter, lambda function expression

高洛峰
高洛峰Original
2016-10-20 10:01:561463browse

filter(function or None, sequence), where sequence can be list, tuple, string. The function of this function is to filter out all elements in the sequence that return True or bool (return value) as True when the function is called with the element itself as a parameter and return it as a list. The filter can only accept two parameters (function, sequence), among which the function Only one value can be returned in the function

Let’s start with a simple code:

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

The code means to output the divisor of the largest three-digit number of 555555.

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

filter() function, which is used to filter lists. The simplest way to put it is to use a function to filter a list, pass each item in the list into the filter function, and delete the item from the list when the filter function returns false.

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

Simply speaking, 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 users to quickly define a single-line minimal function , these functions, called lambdas, are borrowed from Lisp.

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

As you can see from the code, the lambda function completes the same thing as the ordinary function, and the lambda has no brackets around the parameter list and ignores the return keyword (return exists implicitly because the entire function only has one line , and the function has no name, but it can be assigned to a variable and called)

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


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Powerful zipNext article:Powerful zip