【python基础】十个例子学会reduce函数

0 引文

其实这篇文章之前就发了,由于遇到了一个bug(或者说是特性),只好现在重新码一遍/(ㄒoㄒ)/~~

1 文档

functools.reduce(function, iterable[, initializer])

Apply function of two arguments cumulatively to the items of iterable, from left to right, so as to reduce the iterable to a single value. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5). The left argument, x, is the accumulated value and the right argument, y, is the update value from the iterable. If the optional initializer is present, it is placed before the items of the iterable in the calculation, and serves as a default when the iterable is empty. If initializer is not given and iterable contains only one item, the first item is returned.

Roughly equivalent to:

def reduce(function, iterable, initializer=None):
    it = iter(iterable)
    if initializer is None:
        value = next(it)
    else:
        value = initializer
    for element in it:
        value = function(value, element)
    return value

See itertools.accumulate() for an iterator that yields all intermediate values.

2 分析

reduce 有 三个参数:

参数 说明
function 有两个参数的函数
iterable tuple ,list ,dictionary, string等可迭代对象
initializer 初始值, 可选

3 用例

①累加

from functools import reduce
import operator

nums=[1,2,3,4,5]
res=reduce(operator.add,nums)   # 15
# res=reduce(lambda x,y:x+y,nums)
print(res)

②累乘

nums=[1,2,3,4,5]
res=reduce(operator.mul,nums)   # 120
print(res)

③阶乘

from functools import reduce
import operator

n=5
res=reduce(operator.mul,range(1,n+1))   # 120
print(res)

④最大值

from functools import reduce
import operator

nums=[-1,0x3f,666.6,1_000,0b_101]
res=reduce(lambda x,y:max(x,y),nums)    # 1000
print(res)

⑤整数列表拼成整数

from functools import reduce
import operator

nums=[1,0,2,4]
res=reduce(lambda x,y:x*10+y,nums)    # 1024
print(res)

⑥统计字母数

from functools import reduce
import operator

sentence='I love leetcode very much'.split()
res=reduce(lambda x,y:x+len(y),sentence,0)
print(res)

⑦翻转字符串

from functools import reduce
import operator

sentence='I love leetcode very much'
res=reduce(lambda x,y:y+x,sentence)
print(res)

⑧字典去重

from functools import reduce
from itertools import groupby
import operator

data = [{
    
    'leetcode': 'good'}, {
    
    'leetcode': 'nice'}, {
    
    'leetcode': 'good'},{
    
    'codeforce': 'good'},{
    
    'acwing':'wonderful'}]
res=reduce(lambda x,y:x if y in x else x + [y], [[], ] + data)
print(res)

⑨统计字典信息

problems =[
    {
    
    'name':'两数之和', '题解数量':15931, '难度':'简单'},
    {
    
    'name':'网格照明', '题解数量':122, '难度':'困难'},
    {
    
    'name':'两数相加', '题解数量':8270, '难度':'中等'},
    {
    
    'name':'最长回文子串', '题解数量':4709, '难度':'中等'},
    {
    
    'name': '回文数', '题解数量': 5630, '难度': '简单'},
]

res = reduce(lambda x,y:x+y['题解数量'], problems, 0)   # 34662

print(res)

⑩字典分组

from functools import reduce
import operator

problems =[
    {
    
    'name':'两数之和', '题解数量':15931, '难度':'简单'},
    {
    
    'name':'网格照明', '题解数量':122, '难度':'困难'},
    {
    
    'name':'两数相加', '题解数量':8270, '难度':'中等'},
    {
    
    'name':'最长回文子串', '题解数量':4709, '难度':'中等'},
    {
    
    'name': '回文数', '题解数量': 5630, '难度': '简单'},
]

res = reduce(lambda acc, val: {
    
    **acc, **{
    
    val['难度']: acc[val['难度']]+ [val['name']]}}, problems, {
    
    '简单':[], '中等':[],'困难':[]})
print(res)  # {'简单': ['两数之和', '回文数'], '中等': ['两数相加', '最长回文子串'], '困难': ['网格照明']}

4 accumulate

reduce和accumulate两者都是有关累积的函数,除了reduce来自functools库,accumulate来自itertools库之一区别外,两者本质的区别是:

1 reduce返回累积值
2 accumulate返回一个包括各累积值的迭代器

猜你喜欢

转载自blog.csdn.net/weixin_45825073/article/details/122821738
今日推荐