Reductionist in Python: as a shorthand but providing a list of intermediate results

You know a handy feature reducein Python. For example, you can use it to summarize the list (pretend that there is no built-in sum ):

reduce(lambda x,y: x+y, [1,2,3,4], 0)

which returns (((0 + 1) +2) +3) +4 = 10.

Now, if I need a list of subtotals? In this case [1,3,6,10].

Here's an ugly solution. Is there anything more pythonic?

def reducelist(f, l, x): 
  out = [x]
  prev = x
  for i in l:
    prev = f(prev, i)
    out.append(prev)
  return out
+5
source share
2 answers

My favorite, if you are fairly recent:

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 also takes a function argument [even later 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]
+8
source

. x :

def reducelist(f, lst, x=0): 
  prev = x
  for i in lst: 
    prev = f(prev, i)
    yield prev

pythonic.

+8

All Articles