使用 reduce() 的有用代码? [英] Useful code which uses reduce()?

查看:16
本文介绍了使用 reduce() 的有用代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里有人有在python中使用reduce()函数的有用代码吗?除了我们在示例中看到的通常的 + 和 * 之外,还有其他代码吗?

Does anyone here have any useful code which uses reduce() function in python? Is there any code other than the usual + and * that we see in the examples?

参考 Python 3000 中的 reduce() 的命运 by GvR

推荐答案

我发现除了 + 和 * 之外的其他用途是 with and and or,但现在我们有了 anyall 来替换这些情况.

The other uses I've found for it besides + and * were with and and or, but now we have any and all to replace those cases.

foldlfoldr 在 Scheme 中经常出现......

foldl and foldr do come up in Scheme a lot...

这里有一些可爱的用法:

Here's some cute usages:

扁平化列表

目标:将[[1, 2, 3], [4, 5], [6, 7, 8]]转化为[1, 2, 3, 4, 5, 6, 7, 8].

reduce(list.__add__, [[1, 2, 3], [4, 5], [6, 7, 8]], [])

数字到数字的列表

目标:将[1, 2, 3, 4, 5, 6, 7, 8]变成12345678.

丑陋,缓慢的方式:

int("".join(map(str, [1,2,3,4,5,6,7,8])))

漂亮的reduce方式:

reduce(lambda a,d: 10*a+d, [1,2,3,4,5,6,7,8], 0)

这篇关于使用 reduce() 的有用代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆