Home > Backend Development > Python Tutorial > Python zero-based introduction to lambda expressions and built-in functions of filter and map

Python zero-based introduction to lambda expressions and built-in functions of filter and map

黄舟
Release: 2017-01-16 14:13:35
Original
1715 people have browsed it

1.Lambda expression
The syntax of Lambda expression is: lambda parameter: operation on the parameter
The reason why Lambda expression is introduced is mainly due to the following points:
(1) Python writing When executing scripts, using lanbda can save the process of defining functions.
(2) For some more abstract functions that only need to be called once or twice to execute the entire program, there is no need to worry about naming issues. .
(3) Simplify the readability of the code. There is no need to go to the definition part of the function to read.

Note that when using Lambda expressions, first assign the Lambda expression to a variable, and then Use this variable as if calling a function to get the result of the operation.

def ds(x):
     return 2*x+1print(ds(5))
#lambda表达式后面紧跟着的是参数,冒号后面
#紧跟着的是对于参数进行的操作
lambda x:2*x+1g=lambda x:2*x+1
print(g(5))def add(x,y):
     return (x+y)
print(add(3,4))

g=lambda x,y : x+y
print(g(3,4))
Copy after login

Python zero-based introduction to lambda expressions and built-in functions of filter and map

2.filter() function
Syntax: filter(None or Function, iterable)
The function is to select the iterable data through conditions Data with a result of 1 or true is more convenient to use in combination with lambda.
The function of the filter in the example code is to filter out odd numbers between 1 and 10

list1=list(filter(lambda x:x%2,range(0,10)))
print(list1)
Copy after login

Python zero-based introduction to lambda expressions and built-in functions of filter and map

3.map() function
The map() function calculates the iterable data one by one according to the mapping defined by the first parameter.

list2=list(map(lambda x:x*2,range(10)))
print(list2)
Copy after login

Python zero-based introduction to lambda expressions and built-in functions of filter and map

The basic knowledge about functions ends here. The next blog will collect relevant knowledge about data structures such as dictionaries.


The above is the content of lambda expressions and filter and map built-in functions in Part 8 of Python Zero Basic Introduction. For more related content, please pay attention to the PHP Chinese website (www.php. cn)!


Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template