diff options
Diffstat (limited to 'Doc/library/itertools.rst')
| -rw-r--r-- | Doc/library/itertools.rst | 27 |
1 files changed, 25 insertions, 2 deletions
diff --git a/Doc/library/itertools.rst b/Doc/library/itertools.rst index add2091..757823d 100644 --- a/Doc/library/itertools.rst +++ b/Doc/library/itertools.rst @@ -46,6 +46,7 @@ Iterator Arguments Results ==================== ============================ ================================================= ============================================================= Iterator Arguments Results Example ==================== ============================ ================================================= ============================================================= +:func:`accumulate` p 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,22 @@ 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) + + Make an iterator that returns accumulated sums. Elements may be any addable + type including :class:`Decimal` or :class:`Fraction`. Equivalent to:: + + def accumulate(iterable): + 'Return running totals' + # accumulate([1,2,3,4,5]) --> 1 3 6 10 15 + it = iter(iterable) + total = next(it) + yield total + for element in it: + total = total + element + yield total + + .. versionadded:: 3.2 .. function:: chain(*iterables) @@ -560,8 +577,8 @@ loops that truncate the stream. .. _itertools-recipes: -Recipes -------- +Itertools Recipes +----------------- This section shows recipes for creating an extended toolset using the existing itertools as building blocks. @@ -653,6 +670,12 @@ which incur interpreter overhead. pending -= 1 nexts = cycle(islice(nexts, pending)) + 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 + t1, t2 = tee(iterable) + return filterfalse(pred, t1), filter(pred, t2) + def powerset(iterable): "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)" s = list(iterable) |
