对将一个可迭代数据集合中的所有数据进行累积。
reduce() 原理图Apply a function of two arguments cumulatively to the items of a sequence, from left to right, so as to reduce the sequence to a single value.
For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates((((1+2)+3)+4)+5).
If initial is present, it is placed before the items of the sequence in the calculation, and serves as a default when the
sequence is empty.
from functools import reduce
reduce(function, iterable[, initializer])
-
function
函数,两个参数 -
sequence
可迭代的 - tuple/list/dict/str -
initial
可选参数。初始值。如果有initial
,计算时初始值放在所有项前面
Python 3.8.0 (tags/v3.8.0:fa919fd, Oct 14 2019, 19:21:23) [MSC v.1916 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from functools import reduce
>>>
>>> def add(x,y):
... return x+y
...
>>> reduce(add,[1,2,3,4])
10
- 使用
lambda
# 累加
>>> reduce(lambda x,y:x+y, [1,2,3,4])
10
# 把列表中数按位拼成整数
>>> reduce(lambda x,y: x*10+y, [1,2,3])
123
- 增加初始值
>>> reduce(lambda x,y:x+y, [1,2,3,4], 1)
11
# 逆序字符串
>>> reduce(lambda x,y:y+x, 'abcdefg')
'gfedcba'
>>> reduce(lambda x,y:y+x, 'abcdefg','xyz')
'gfedcbaxyz'
- 进阶
from functools import reduce
import collections
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, collections.defaultdict(list))
print(grouped)
等同于 groupby
import itertools
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'})
grouped = {item[0]:list(item[1])
for item in itertools.groupby(scientists, lambda x: x['gender'])}
print(grouped)
网友评论