lambda Expression is ⼀⾏ function , They're in other languages ⾔ Also known as anonymous functions without specific names .lambda Expressions are very useful , It makes the code simpler . If you don't want to be programmed with ⼀ Functions that make ⽤ two , Maybe you think ⽤lambda expression , They're completely... Like ordinary functions ⼀ sample . Let's take a look lambda The prototype of an expression 、 Code case 、 Sort the list 、 List and ⾏ Sorting and lambda The pros and cons of expressions !
1、 Prototype :
lambda In the sentence , The colon is preceded by a parameter , There can be multiple , Separated by commas , The return value to the right of the colon .lambda Statement is actually a function object . If there are no parameters , be lambda There's No... before the colon .
lambda Parameters : operation ( Parameters )
2、 Code case :
add = lambda x, y: x + y
print(add(3, 5))
# Output: 8
3、 Sort the list
a = [(1, 2), (4, 1), (9, 10), (13, -3)]
a.sort(key=lambda x: x[1])
print(a)
# Output: [(13, -3), (4, 1), (1, 2), (9, 10)]
4、 List and ⾏ Sort
data = zip(list1, list2)
data.sort()
list1, list2 = map(lambda t: list(t), zip(*data))
5、lambda The pros and cons of expressions
Python Medium function ratio lambda Expressions are more functional and adaptable , therefore lambda Expressions create simple function objects . But on the other hand ,lambda The advantages of expressions are also obvious . such as , For single line code functions , Use lambda Expressions can eliminate the complex process of defining functions , Make your code cleaner . And for functions that don't need to be used many times , because lambda The characteristic of an expression that is released immediately after it is used up , Improve the performance of the program .
About Python Medium lambda This is the end of the expression learning summary , In general ,lambda Expressions play an extremely important role , But we should also pay attention not to abuse and overuse lambda expression .
Zhengzhou infertility hospital where good _ Which habits lead to uterine displacement :https://yyk.fh21.com.cn/hospital_6369/tsyl/16699557.html
Zhengzhou infertility hospital which good _ How to prepare for pregnancy for women with palace cold :https://yyk.fh21.com.cn/hospital_6369/tsyl/16699559.html
Shangqiu infertility hospital _ What do you need to pay attention to before salpingography :https://yyk.fh21.com.cn/hospital_6369/tsyl/16699590.html