diff options
author | Raymond Hettinger <python@rcn.com> | 2010-03-28 18:12:35 (GMT) |
---|---|---|
committer | Raymond Hettinger <python@rcn.com> | 2010-03-28 18:12:35 (GMT) |
commit | 6044655d59d33c7a5e5ca439b564ee753610b789 (patch) | |
tree | b699d7bb968c35a2ea45237acb2c5724c7fb9a2d /Doc/library/itertools.rst | |
parent | 3522e040715cc79a62da76209d7ca50eab6f82c0 (diff) | |
download | cpython-6044655d59d33c7a5e5ca439b564ee753610b789.zip cpython-6044655d59d33c7a5e5ca439b564ee753610b789.tar.gz cpython-6044655d59d33c7a5e5ca439b564ee753610b789.tar.bz2 |
Update itertools recipes.
Diffstat (limited to 'Doc/library/itertools.rst')
-rw-r--r-- | Doc/library/itertools.rst | 34 |
1 files changed, 27 insertions, 7 deletions
diff --git a/Doc/library/itertools.rst b/Doc/library/itertools.rst index 14a7afd..f3e107e2 100644 --- a/Doc/library/itertools.rst +++ b/Doc/library/itertools.rst @@ -632,9 +632,6 @@ which incur interpreter overhead. "Return first n items of the iterable as a list" return list(islice(iterable, n)) - def enumerate(iterable, start=0): - return izip(count(start), iterable) - def tabulate(function, start=0): "Return function(0), function(1), ..." return imap(function, count(start)) @@ -741,10 +738,9 @@ which incur interpreter overhead. seen = set() seen_add = seen.add if key is None: - for element in iterable: - if element not in seen: - seen_add(element) - yield element + for element in ifilterfalse(seen.__contains__, iterable): + seen_add(element) + yield element else: for element in iterable: k = key(element) @@ -758,6 +754,30 @@ which incur interpreter overhead. # unique_justseen('ABBCcAD', str.lower) --> A B C A D return imap(next, imap(itemgetter(1), groupby(iterable, key))) + def iter_except(func, exception, first=None): + """ Call a function repeatedly until an exception is raised. + + Converts a call-until-exception interface to an iterator interface. + Like __builtin__.iter(func, sentinel) but uses an exception instead + of a sentinel to end the loop. + + Examples: + bsddbiter = iter_except(db.next, bsddb.error, db.first) + heapiter = iter_except(functools.partial(heappop, h), IndexError) + dictiter = iter_except(d.popitem, KeyError) + dequeiter = iter_except(d.popleft, IndexError) + queueiter = iter_except(q.get_nowait, Queue.Empty) + setiter = iter_except(s.pop, KeyError) + + """ + try: + if first is not None: + yield first() + while 1: + yield func() + except exception: + pass + Note, many of the above recipes can be optimized by replacing global lookups with local variables defined as default values. For example, the *dotproduct* recipe can be written as:: |