The use of filter and lambda functions in Python is briefly described

  • 2020-05-07 19:53:58
  • OfStack

filter(function or None, sequence), where sequence can be list,tuple,string. This function filters out all the elements in sequence.

filter(function or None, sequence), where sequence can be list,tuple,string. This function filters out all elements in sequence that return True or bool(return value) True when the element itself is called as an argument to function and returns it as a list. filter can only accept two arguments (function,sequence), of which the function function can only return one value

Let's start with a simple code:
 


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

The code means what is the divisor of the largest 3-digit number to output 555555.

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

The filter() function is used to filter lists. The simplest way to say this is to filter a list with 1 function, pass each item of the list into the filter function, and the filter function returns false and removes the item from the list.

The filter() function takes two arguments, 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 or not, and finally returns a new list.

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


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

The second thing is the lambda() function

Python supports this syntax and allows the user to quickly define the smallest single-line functions, which are called lambda and 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 does the same thing as a normal function, and lambda has no parentheses around the argument list and ignores the return keyword (return is implied because the entire function has only 1 line, and the function has no name, but it can be assigned to a variable to be called).

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


Related articles: