Accumulate function in python
Mick Krippendorf
mad.mick at gmx.de
Mon Jul 19 08:14:15 EDT 2010
Am 19.07.2010 13:18, dhruvbird wrote:
> Hello,
> I have a list of integers: x = [ 0, 1, 2, 1, 1, 0, 0, 2, 3 ]
> And would like to compute the cumulative sum of all the integers
> from index zero into another array. So for the array above, I should
> get: [ 0, 1, 3, 4, 5, 5, 5, 7, 10 ]
> What is the best way (or pythonic way) to get this.
<python>
import copy
import itertools
def acc(items, copy=copy.deepcopy):
items = iter(items)
result = next(items)
yield copy(result)
for item in items:
result += item
yield copy(result)
print list(acc([0, 1, 2, 1, 1, 0, 0, 2, 3]))
print list(itertools.islice(acc(itertools.count()), 10))
print list(acc(['a', 'b', 'c']))
print list(acc([[a], [b], [c]]))
</python>
Output:
[0, 1, 3, 4, 5, 5, 5, 7, 10]
[0, 1, 3, 6, 10, 15, 21, 28, 36, 45]
['a', 'ab', 'abc']
[[a], [a, b], [a, b, c]]
Without copy.deepcopy() the last line would be:
[[a, b, c], [a, b, c], [a, b, c]]
The copy=copy.deepcopy parameter allows for things like this:
>>> print list(acc([[a], [b], [c]], tuple))
[(a,), (a, b), (a, b, c)]
or:
>>> print list(acc([['a'], ['b'], ['f'], ['s'], ['c'], ['g']], max))
['a', 'b', 'f', 's', 's', 's']
or:
>>> data = [[0], [1], [2], [1], [1], [2], [3]]
>>> print list(acc(data, lambda x: float(sum(x)) / float(len(x))))
[0.0, 0.5, 1.0, 1.0, 1.0, 1.1666666666666667, 1.4285714285714286]
Endless possibilities in an endless universe.
Regards,
Mick.
More information about the Python-list
mailing list