diff options
author | Raymond Hettinger <python@rcn.com> | 2003-09-08 23:58:40 (GMT) |
---|---|---|
committer | Raymond Hettinger <python@rcn.com> | 2003-09-08 23:58:40 (GMT) |
commit | a098b33c9346ae8c8891982cd733d5d9dcdae2ec (patch) | |
tree | 0f79aae580e1af9335a3b0f9fc77d27db5bbb978 /Doc | |
parent | 9d50d91e77974c233c1c136f1a7a8ce7d53cea09 (diff) | |
download | cpython-a098b33c9346ae8c8891982cd733d5d9dcdae2ec.zip cpython-a098b33c9346ae8c8891982cd733d5d9dcdae2ec.tar.gz cpython-a098b33c9346ae8c8891982cd733d5d9dcdae2ec.tar.bz2 |
Add an example to address a common question of how to split iterators.
Diffstat (limited to 'Doc')
-rw-r--r-- | Doc/lib/libitertools.tex | 27 |
1 files changed, 20 insertions, 7 deletions
diff --git a/Doc/lib/libitertools.tex b/Doc/lib/libitertools.tex index 7fdd602..453d16e 100644 --- a/Doc/lib/libitertools.tex +++ b/Doc/lib/libitertools.tex @@ -321,13 +321,15 @@ Samuele \end{verbatim} -This section has further examples of how itertools can be combined. -Note that \function{enumerate()} and \method{iteritems()} already -have highly efficient implementations in Python. They are only -included here to illustrate how higher level tools can be created -from building blocks. +This section shows how itertools can be combined to create other more +powerful itertools. Note that \function{enumerate()} and \method{iteritems()} +already have efficient implementations in Python. They are only included here +to illustrate how higher level tools can be created from building blocks. \begin{verbatim} +def take(n, seq): + return list(islice(seq, n)) + def enumerate(iterable): return izip(count(), iterable) @@ -380,7 +382,18 @@ def window(seq, n=2): result = result[1:] + (elem,) yield result -def take(n, seq): - return list(islice(seq, n)) +def tee(iterable): + "Return two independent iterators from a single iterable" + def gen(next, data={}, cnt=[0]): + dpop = data.pop + for i in count(): + if i == cnt[0]: + item = data[i] = next() + cnt[0] += 1 + else: + item = dpop(i) + yield item + next = iter(iterable).next + return (gen(next), gen(next)) \end{verbatim} |