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

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

问题描述

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

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

解决方案 any 和 all 来代替这些情况。

foldl foldr 会出现在Scheme a很多...



以下是一些可爱的用法:

拼合列表



目标:转到 [[1,2,3],[4,5],[6,7,8]] 转换为 [1,2,3,4,5,6,7,8]



<$ p $ b $ reduce(list .__ add__,[[1,2,3],[4,5],[6,7,8]],[])



$ b

目标数字列表

:将 [1,2,3,4,5,6,7,8] 转换为 12345678 p>

丑陋,缓慢的方式:

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



<

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


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?

Refer Fate of reduce() in Python 3000 by GvR

解决方案

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.

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

Here's some cute usages:

Flatten a list

Goal: turn [[1, 2, 3], [4, 5], [6, 7, 8]] into [1, 2, 3, 4, 5, 6, 7, 8].

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

List of digits to a number

Goal: turn [1, 2, 3, 4, 5, 6, 7, 8] into 12345678.

Ugly, slow way:

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

Pretty reduce way:

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

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

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