Commit 040f10e9 authored by Raymond Hettinger's avatar Raymond Hettinger

Add examples.

parent 4291b19d
...@@ -71,6 +71,7 @@ loops that truncate the stream. ...@@ -71,6 +71,7 @@ loops that truncate the stream.
Equivalent to:: Equivalent to::
def chain(*iterables): def chain(*iterables):
# chain('ABC', 'DEF') --> A B C D E F
for it in iterables: for it in iterables:
for element in it: for element in it:
yield element yield element
...@@ -83,6 +84,7 @@ loops that truncate the stream. ...@@ -83,6 +84,7 @@ loops that truncate the stream.
@classmethod @classmethod
def from_iterable(iterables): def from_iterable(iterables):
# chain.from_iterable(['ABC', 'DEF']) --> A B C D E F
for it in iterables: for it in iterables:
for element in it: for element in it:
yield element yield element
...@@ -108,7 +110,8 @@ loops that truncate the stream. ...@@ -108,7 +110,8 @@ loops that truncate the stream.
Equivalent to:: Equivalent to::
def combinations(iterable, r): def combinations(iterable, r):
'combinations(range(4), 3) --> (0,1,2) (0,1,3) (0,2,3) (1,2,3)' # combinations('ABCD', 2) --> AB AC AD BC BD CD
# combinations(range(4), 3) --> 012 013 023 123
pool = tuple(iterable) pool = tuple(iterable)
n = len(pool) n = len(pool)
indices = range(r) indices = range(r)
...@@ -145,6 +148,7 @@ loops that truncate the stream. ...@@ -145,6 +148,7 @@ loops that truncate the stream.
numbers. Equivalent to:: numbers. Equivalent to::
def count(n=0): def count(n=0):
# count(10) --> 10 11 12 13 14 ...
while True: while True:
yield n yield n
n += 1 n += 1
...@@ -157,6 +161,7 @@ loops that truncate the stream. ...@@ -157,6 +161,7 @@ loops that truncate the stream.
indefinitely. Equivalent to:: indefinitely. Equivalent to::
def cycle(iterable): def cycle(iterable):
# cycle('ABCD') --> A B C D A B C D A B C D ...
saved = [] saved = []
for element in iterable: for element in iterable:
yield element yield element
...@@ -177,6 +182,7 @@ loops that truncate the stream. ...@@ -177,6 +182,7 @@ loops that truncate the stream.
start-up time. Equivalent to:: start-up time. Equivalent to::
def dropwhile(predicate, iterable): def dropwhile(predicate, iterable):
# dropwhile(lambda x: x<5, [1,4,6,4,1]) --> 6 4 1
iterable = iter(iterable) iterable = iter(iterable)
for x in iterable: for x in iterable:
if not predicate(x): if not predicate(x):
...@@ -215,6 +221,8 @@ loops that truncate the stream. ...@@ -215,6 +221,8 @@ loops that truncate the stream.
:func:`groupby` is equivalent to:: :func:`groupby` is equivalent to::
class groupby(object): class groupby(object):
# [k for k, g in groupby('AAAABBBCCDAABBB')] --> A B C D A B
# [(list(g)) for k, g in groupby('AAAABBBCCD')] --> AAAA BBB CC D
def __init__(self, iterable, key=None): def __init__(self, iterable, key=None):
if key is None: if key is None:
key = lambda x: x key = lambda x: x
...@@ -245,6 +253,7 @@ loops that truncate the stream. ...@@ -245,6 +253,7 @@ loops that truncate the stream.
that are true. Equivalent to:: that are true. Equivalent to::
def ifilter(predicate, iterable): def ifilter(predicate, iterable):
# ifilter(lambda x: x%2, range(10)) --> 1 3 5 7 9
if predicate is None: if predicate is None:
predicate = bool predicate = bool
for x in iterable: for x in iterable:
...@@ -259,6 +268,7 @@ loops that truncate the stream. ...@@ -259,6 +268,7 @@ loops that truncate the stream.
that are false. Equivalent to:: that are false. Equivalent to::
def ifilterfalse(predicate, iterable): def ifilterfalse(predicate, iterable):
# ifilterfalse(lambda x: x%2, range(10)) --> 0 2 4 6 8
if predicate is None: if predicate is None:
predicate = bool predicate = bool
for x in iterable: for x in iterable:
...@@ -277,6 +287,7 @@ loops that truncate the stream. ...@@ -277,6 +287,7 @@ loops that truncate the stream.
useful way of supplying arguments to :func:`imap`. Equivalent to:: useful way of supplying arguments to :func:`imap`. Equivalent to::
def imap(function, *iterables): def imap(function, *iterables):
# imap(pow, (2,3,10), (5,2,3)) --> 32 9 1000
iterables = map(iter, iterables) iterables = map(iter, iterables)
while True: while True:
args = [it.next() for it in iterables] args = [it.next() for it in iterables]
...@@ -299,6 +310,10 @@ loops that truncate the stream. ...@@ -299,6 +310,10 @@ loops that truncate the stream.
multi-line report may list a name field on every third line). Equivalent to:: multi-line report may list a name field on every third line). Equivalent to::
def islice(iterable, *args): def islice(iterable, *args):
# islice('ABCDEFG', 2) --> A B
# islice('ABCDEFG', 2, 4) --> C D
# islice('ABCDEFG', 2, None) --> C D E F G
# islice('ABCDEFG', 0, None, 2) --> A C E G
s = slice(*args) s = slice(*args)
it = iter(xrange(s.start or 0, s.stop or sys.maxint, s.step or 1)) it = iter(xrange(s.start or 0, s.stop or sys.maxint, s.step or 1))
nexti = it.next() nexti = it.next()
...@@ -321,6 +336,7 @@ loops that truncate the stream. ...@@ -321,6 +336,7 @@ loops that truncate the stream.
lock-step iteration over several iterables at a time. Equivalent to:: lock-step iteration over several iterables at a time. Equivalent to::
def izip(*iterables): def izip(*iterables):
# izip('ABCD', 'xy') --> Ax By
iterables = map(iter, iterables) iterables = map(iter, iterables)
while iterables: while iterables:
result = [it.next() for it in iterables] result = [it.next() for it in iterables]
...@@ -346,6 +362,7 @@ loops that truncate the stream. ...@@ -346,6 +362,7 @@ loops that truncate the stream.
Iteration continues until the longest iterable is exhausted. Equivalent to:: Iteration continues until the longest iterable is exhausted. Equivalent to::
def izip_longest(*args, **kwds): def izip_longest(*args, **kwds):
# izip_longest('ABCD', 'xy', fillvalue='-') --> Ax By C- D-
fillvalue = kwds.get('fillvalue') fillvalue = kwds.get('fillvalue')
def sentinel(counter = ([fillvalue]*(len(args)-1)).pop): def sentinel(counter = ([fillvalue]*(len(args)-1)).pop):
yield counter() # yields the fillvalue, or raises IndexError yield counter() # yields the fillvalue, or raises IndexError
...@@ -382,7 +399,8 @@ loops that truncate the stream. ...@@ -382,7 +399,8 @@ loops that truncate the stream.
Equivalent to:: Equivalent to::
def permutations(iterable, r=None): def permutations(iterable, r=None):
'permutations(range(3), 2) --> (0,1) (0,2) (1,0) (1,2) (2,0) (2,1)' # permutations('ABCD', 2) --> AB AC AD BA BC BD CA CB CD DA DB DC
# permutations(range(3)) --> 012 021 102 120 201 210
pool = tuple(iterable) pool = tuple(iterable)
n = len(pool) n = len(pool)
r = n if r is None else r r = n if r is None else r
...@@ -424,8 +442,8 @@ loops that truncate the stream. ...@@ -424,8 +442,8 @@ loops that truncate the stream.
Equivalent to nested for-loops in a generator expression. For example, Equivalent to nested for-loops in a generator expression. For example,
``product(A, B)`` returns the same as ``((x,y) for x in A for y in B)``. ``product(A, B)`` returns the same as ``((x,y) for x in A for y in B)``.
The leftmost iterators are in the outermost for-loop, so the output tuples The leftmost iterators correspond to the outermost for-loop, so the output
cycle like an odometer (with the rightmost element changing on every tuples cycle like an odometer (with the rightmost element changing on every
iteration). This results in a lexicographic ordering so that if the iteration). This results in a lexicographic ordering so that if the
inputs iterables are sorted, the product tuples are emitted inputs iterables are sorted, the product tuples are emitted
in sorted order. in sorted order.
...@@ -438,6 +456,8 @@ loops that truncate the stream. ...@@ -438,6 +456,8 @@ loops that truncate the stream.
actual implementation does not build up intermediate results in memory:: actual implementation does not build up intermediate results in memory::
def product(*args, **kwds): def product(*args, **kwds):
# product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
# product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
pools = map(tuple, args) * kwds.get('repeat', 1) pools = map(tuple, args) * kwds.get('repeat', 1)
result = [[]] result = [[]]
for pool in pools: for pool in pools:
...@@ -451,10 +471,11 @@ loops that truncate the stream. ...@@ -451,10 +471,11 @@ loops that truncate the stream.
Make an iterator that returns *object* over and over again. Runs indefinitely Make an iterator that returns *object* over and over again. Runs indefinitely
unless the *times* argument is specified. Used as argument to :func:`imap` for unless the *times* argument is specified. Used as argument to :func:`imap` for
invariant parameters to the called function. Also used with :func:`izip` to invariant function parameters. Also used with :func:`izip` to create constant
create an invariant part of a tuple record. Equivalent to:: fields in a tuple record. Equivalent to::
def repeat(object, times=None): def repeat(object, times=None):
# repeat(10, 3) --> 10 10 10
if times is None: if times is None:
while True: while True:
yield object yield object
...@@ -472,6 +493,7 @@ loops that truncate the stream. ...@@ -472,6 +493,7 @@ loops that truncate the stream.
between ``function(a,b)`` and ``function(*c)``. Equivalent to:: between ``function(a,b)`` and ``function(*c)``. Equivalent to::
def starmap(function, iterable): def starmap(function, iterable):
# starmap(pow, [(2,5), (3,2), (10,3)]) --> 32 9 1000
for args in iterable: for args in iterable:
yield function(*args) yield function(*args)
...@@ -485,6 +507,7 @@ loops that truncate the stream. ...@@ -485,6 +507,7 @@ loops that truncate the stream.
predicate is true. Equivalent to:: predicate is true. Equivalent to::
def takewhile(predicate, iterable): def takewhile(predicate, iterable):
# takewhile(lambda x: x<5, [1,4,6,4,1]) --> 1 4
for x in iterable: for x in iterable:
if predicate(x): if predicate(x):
yield x yield x
...@@ -528,23 +551,6 @@ Examples ...@@ -528,23 +551,6 @@ Examples
The following examples show common uses for each tool and demonstrate ways they The following examples show common uses for each tool and demonstrate ways they
can be combined. :: can be combined. ::
>>> amounts = [120.15, 764.05, 823.14]
>>> for checknum, amount in izip(count(1200), amounts):
... print 'Check %d is for $%.2f' % (checknum, amount)
...
Check 1200 is for $120.15
Check 1201 is for $764.05
Check 1202 is for $823.14
>>> import operator
>>> for cube in imap(operator.pow, xrange(1,5), repeat(3)):
... print cube
...
1
8
27
64
# Show a dictionary sorted and grouped by value # Show a dictionary sorted and grouped by value
>>> from operator import itemgetter >>> from operator import itemgetter
>>> d = dict(a=1, b=2, c=1, d=2, e=1, f=2, g=3) >>> d = dict(a=1, b=2, c=1, d=2, e=1, f=2, g=3)
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment