Add itertools.accumulate().

This commit is contained in:
Raymond Hettinger 2010-12-01 22:50:36 +00:00
parent 482ba77245
commit adb8146e53

View file

@ -46,6 +46,7 @@ Iterator Arguments Results
==================== ============================ ================================================= =============================================================
Iterator Arguments Results Example
==================== ============================ ================================================= =============================================================
:func:`accumulate` p[, start=0] p0, p0+p1, p0+p1+p2 ... ` ``accumulate([1,2,3,4,5]) --> 1 3 6 10 15``
:func:`chain` p, q, ... p0, p1, ... plast, q0, q1, ... ``chain('ABC', 'DEF') --> A B C D E F``
:func:`compress` data, selectors (d[0] if s[0]), (d[1] if s[1]), ... ``compress('ABCDEF', [1,0,1,0,1,1]) --> A C E F``
:func:`dropwhile` pred, seq seq[n], seq[n+1], starting when pred fails ``dropwhile(lambda x: x<5, [1,4,6,4,1]) --> 6 4 1``
@ -83,6 +84,21 @@ The following module functions all construct and return iterators. Some provide
streams of infinite length, so they should only be accessed by functions or
loops that truncate the stream.
.. function:: accumulate(iterable, start=0)
Make an iterator that returns accumulated sums plus the value of the *start*
parameter (which defaults to :const:`0`). Elements may be any addable type
including :class:`Decimal` or :class:`Fraction`. Equivalent to::
def accumulate(iterable, start=0):
'Return running totals'
# accumulate([1,2,3,4,5]) --> 1 3 6 10 15
total = start
for element in iterable:
total += element
yield total
.. versionadded:: 3.2
.. function:: chain(*iterables)
@ -653,14 +669,6 @@ which incur interpreter overhead.
pending -= 1
nexts = cycle(islice(nexts, pending))
def accumulate(iterable):
'Emit a running total'
# accumulate([1,2,3,4,5]) --> 1 3 6 10 15
total = 0
for element in iterable:
total += element
yield total
def partition(pred, iterable):
'Use a predicate to partition entries into false entries and true entries'
# partition(is_odd, range(10)) --> 0 2 4 6 8 and 1 3 5 7 9