使用reduce()的有用代码? [英] Useful code which uses reduce()?
问题描述
这里有人有没有使用python中的reduce()函数的有用代码?除了我们在例子中看到的通常的+和*之外,还有其他代码吗?
请参阅 Python 3000中reduce()的命运 by GvR
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]],[])
$ c
$ 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屋!