functool.reduce()函数 Python

2020-04-30  本文已影响0人  RayRaymond

对将一个可迭代数据集合中的所有数据进行累积。

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.

reduce() 原理图
from functools import reduce


reduce(function, iterable[, initializer])
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
# 累加
>>> 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)
上一篇 下一篇

猜你喜欢

热点阅读