python 的 lambda 表达式
python写一些执行脚本时,使用lambda就可以省下定义函数的过程,比如说我们只是需要写个简单的脚本来管理服务器时,我们就不用专门定义函数然后再写调用,使用lambda就可以是代码更加
精简。
对于一些执行下来只要一两次的函数,有时候给函数取名就会成为很麻烦的问题,使用lambda就不用考虑给函数命名的问题了。
#普通的定义函数 def lam(x): return x*x+1 print(lam(5))
lambda表达式
#注意必须要吧lambda表达式的值赋给一个变量 y=lambda x : x * x + 1 print(y(5))
如果要传多个参数也是可以的
#普通的定义函数 def lam(x,y): return x+y print(lam(5,6))
lambda表达式
#要接收多个变量就用英文状态下的逗号隔开就行了 y=lambda x,y : x + y print(y(5,6))
lambda还可以在用作字典排序
temp = { 'a': 24, 'g': 52, 'i': 12, 'k': 33 } sorted(temp.items(), key=lambda item: item[1]) print(temp)
temp.items() 将字典用元组的方式包裹起来
key = lambda 将字典的key值设为lambda
item:item[1] 取出字典中的 value 值
sorted() 进行反向排序