匿名函数lambda:是指一类无需定义标识符(函数名)的函数或子程序。
lambda 函数可以接收任意多个参数 (包括可选参数) 并且返回单个表达式的值。
要点:
1,lambda 函数不能包含命令,
2,包含的表达式不能超过一个。
传入多个参数的lambda函数
def sum(x,y):
return x+y
用lambda来实现:
p = lambda x,y:x+y
print(p(4,6))
多个参数的lambda形式:
a = lambda x,y,z:(x+8)*y-z
print(a(5,6,8))
reduce
从左到右对一个序列的项累计地应用有两个参数的函数,以此合并序列到一个单一值。
例如,reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) 计算的就是((((1+2)+3)+4)+5)。
如果提供了 initial 参数,计算时它将被放在序列的所有项前面,如果序列是空的,它也就是计算的默认结果值了
>>> def add(x, y):
... return x+y
...
>>> from functools import reduce
>>> reduce(add, [1,2,3,4])
10
>>>
上面这段 reduce 代码,其实就相当于 1 + 2 + 3 + 4 = 10, 如果把加号改成乘号, 就成了阶乘了
当然 仅仅是求和的话还有更简单的方法,如下
>>> sum([1,2,3,4])
10
>>>
把一个整数列表拼成整数
>>> from functools import reduce
>>> reduce(lambda x, y: x * 10 + y, [1 , 2, 3, 4, 5])
12345
>>>
对一个复杂的sequence使用reduce ,看下面代码
from functools import reduce
scientists =({'name':'Alan Turing', 'age':105},
{'name':'Dennis Ritchie', 'age':76},
{'name':'John von Neumann', 'age':114},
{'name':'Guido van Rossum', 'age':61})
def reducer(accumulator , value):
sum = accumulator['age'] + value['age']
return sum
total_age = reduce(reducer, scientists)
print(total_age)
所以代码需要修改
from functools import reduce
scientists =({'name':'Alan Turing', 'age':105, 'gender':'male'},
{'name':'Dennis Ritchie', 'age':76, 'gender':'male'},
{'name':'Ada Lovelace', 'age':202, 'gender':'female'},
{'name':'Frances E. Allen', 'age':84, 'gender':'female'})
def reducer(accumulator , value):
sum = accumulator + value['age']
return sum
total_age = reduce(reducer, scientists, 0)
print(total_age)
这个仍然也可以用 sum 来更简单的完成
sum([x['age'] for x in scientists ])
做点更高级的事情,按性别分组
from functools import reduce
scientists =({'name':'Alan Turing', 'age':105, 'gender':'male'},
{'name':'Dennis Ritchie', 'age':76, 'gender':'male'},
{'name':'Ada Lovelace', 'age':202, 'gender':'female'},
{'name':'Frances E. Allen', 'age':84, 'gender':'female'})
def group_by_gender(accumulator , value):
accumulator[value['gender']].append(value['name'])
return accumulator
grouped = reduce(group_by_gender, scientists, {'male':[], 'female':[]})
print(grouped)
输出
{'male': ['Alan Turing', 'Dennis Ritchie'], 'female': ['Ada Lovelace', 'Frances E. Allen']}
参考:https://www.cnblogs.com/lonkiss/p/understanding-python-reduce-function.html