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

本文详细介绍了Python内置模块functools中的reduce函数,包括其工作原理、参数说明,并通过多个实际案例展示了reduce在累加、累乘、阶乘、查找最大值、字符串操作等方面的应用。此外,还对比了reduce与itertools.accumulate的区别。通过本文,读者将深入理解reduce的使用,并能灵活应用于实际编程中。
摘要由CSDN通过智能技术生成

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有两个参数的函数
iterabletuple ,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返回一个包括各累积值的迭代器

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

可可卷

不要看到我~~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值