Python中的reducelist:类似于reduce,但提供中间结果列表 [英] reducelist in Python: like reduce but giving the list of intermediate results
本文介绍了Python中的reducelist:类似于reduce,但提供中间结果列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
您知道Python中方便的reduce
函数.例如,您可以使用它来汇总这样的列表(假设没有内置的
You know the handy reduce
function in Python. For example, you could use it to sum up a list like so (pretend there isn't the built-in sum):
reduce(lambda x,y: x+y, [1,2,3,4], 0)
返回((((0 + 1)+2)+3)+4 = 10
which returns (((0+1)+2)+3)+4 = 10.
现在,如果我想要一个中间金额列表怎么办?在这种情况下,[1,3,6,10]
.
Now what if I wanted a list of the intermediate sums? In this case, [1,3,6,10]
.
这是一个丑陋的解决方案.还有其他pythonic吗?
Here's an ugly solution. Is there something more pythonic?
def reducelist(f, l, x):
out = [x]
prev = x
for i in l:
prev = f(prev, i)
out.append(prev)
return out
推荐答案
最喜欢的,如果您最近的话:
My favourite, if you're recent enough:
Python 3.2.1 (default, Jul 12 2011, 22:22:01)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import itertools
>>> itertools.accumulate([1,2,3,4])
<itertools.accumulate object at 0x1006baad0>
>>> list(itertools.accumulate([1,2,3,4]))
[1, 3, 6, 10]
accumulate 也接受函数参数[甚至更新,不过-3.3]:
accumulate also accepts a function argument [even more recent, though-- 3.3]:
>>> list(itertools.accumulate([1,2,3,4], lambda x,y: x+y))
[1, 3, 6, 10]
>>> list(itertools.accumulate([1,2,3,4], lambda x,y: x+y+1))
[1, 4, 8, 13]
这篇关于Python中的reducelist:类似于reduce,但提供中间结果列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文