搞懂Python lambda表达式的用法
模板: lambda argument: manipulate(argument)
参数:argument就是这个匿名函数传入的参数,冒号后面是我们对这个参数的操作方法
add_one = lambda x:x+1 # 1个参数,执行操作为+1
add_nums = lambda x,y:x+y # 2个参数,执行操作为相加
print(add_one(2)) # 调用add_one
print(add_nums(3,7)) # 调用add_nums
3
10
numbers = [1,2,3,4,5]
add_one = list(map(lambda n:n+1,numbers)) #map(fun,sequence)
print(list(add_one))
print(tuple(add_one))
[2, 3, 4, 5, 6]
(2, 3, 4, 5, 6)
def add(num):
return num+1
numbers = [1,2,3,4,5]
add_one = list(map(add,numbers))
print(add_one)
print(tuple(add_one))
from datetime import datetime as dt
logs = ['serverLog','appLog','paymentLog']
format ='_{}.py'.format(dt.now().strftime('%d-%m-%y'))
result =list(map(lambda x:x+format,logs)) # 利用map+lambda 实现字符串拼接
print(result)
['serverLog_26-07-20.py', 'appLog_26-07-20.py', 'paymentLog_26-07-20.py']
person =[{'name':'XiaoMing',
'city':'beijing'},
{'name':'XiaoLi',
'city':'shanghai'}]
names=list(map(lambda x:x['name'],person))
print(names)
['XiaoMing', 'XiaoLi']
numbers = [0, 1, 2, -3, 5, -8, 13]
# 提取奇数
result = filter(lambda x: x % 2, numbers)
print("Odd Numbers are :",list(result))
# 提取偶数
result = filter(lambda x: x % 2 == 0, numbers)
print("Even Numbers are :",list(result))
# 提取正数
result = filter(lambda x: x>0, numbers)
print("Positive Numbers are :",list(result))
Odd Numbers are : [1, -3, 5, 13]
Even Numbers are : [0, 2, -8]
Positive Numbers are : [1, 2, 5, 13]
person =[{'name':'XiaoMing',
'city':'beijing'},
{'name':'XiaoLi',
'city':'shanghai'}]
names=list(filter(lambda x:x['name']=='XiaoMing',person))
print(names)
[{'name': 'XiaoMing', 'city': 'beijing'}]
from functools import reduce # Only Python 3
numbers = [1,2,3,4]
result_multiply = reduce((lambda x, y: x * y), numbers)
result_add = reduce((lambda x,y: x+y), numbers)
print(result_multiply)
print(result_add)
24
10
可以立即传递(无需变量)
只需一行代码,简洁(未必高效)
可以会自动返回,无需return
lambda函数没有函数名称
from functools import reduce # Only Python 3
numbers = [1,2,3,4]
result_multiply = reduce((lambda x, y: x * y), numbers)
result_add = reduce((lambda x,y: x+y), numbers)
from functools import reduce
from operator import mul
numbers = [1,2,3,4]
result_add = sum(numbers)
result_multiply =reduce(mul,numbers)
print(result_add)
print(result_multiply)
10
24
colors = ['red','purple','green','blue']
result = map(lambda c:c.capitalize(),colors)
print(list(result))
['Red', 'Purple', 'Green', 'Blue']
colors = ['red','purple','green','blue']
result = [c.capitalize() for c in colors]
print(result)
['Red', 'Purple', 'Green', 'Blue']
colors = ['Red','purple','Green','blue']
print(sorted(colors,key=str.capitalize))
['Red', 'Purple', 'Green', 'Blue']
需要处理的方法是很简单的(+1,字符串拼接等),该函数不值得拥有一个名字。
使用lambda表达式,会比我们能想到的函数名称更容易理解。
除了lambda,没有任何python提供的函数可以实现目。
团队中所有成员都熟练掌握了lambda表达式,并且纳入了团队的开发规范。