Kaydet (Commit) 734fb572 authored tarafından Raymond Hettinger's avatar Raymond Hettinger

Add a Guido inspired example for groupby().

üst 57cb68fe
......@@ -406,12 +406,25 @@ Samuele
2 ['b', 'd', 'f']
3 ['g']
# Find runs of consecutive numbers using groupby. The key to the solution
# is differencing with a range so that consecutive numbers all appear in
# same group.
>>> data = [ 1, 4,5,6, 10, 15,16,17,18, 22, 25,26,27,28]
>>> for k, g in groupby(enumerate(data), lambda (i,x):i-x):
... print map(operator.itemgetter(1), g)
...
[1]
[4, 5, 6]
[10]
[15, 16, 17, 18]
[22]
[25, 26, 27, 28]
\end{verbatim}
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
already have efficient implementations. They are included here
to illustrate how higher level tools can be created from building blocks.
\begin{verbatim}
......
......@@ -677,6 +677,20 @@ Samuele
2 ['b', 'd', 'f']
3 ['g']
# Find runs of consecutive numbers using groupby. The key to the solution
# is differencing with a range so that consecutive numbers all appear in
# same group.
>>> data = [ 1, 4,5,6, 10, 15,16,17,18, 22, 25,26,27,28]
>>> for k, g in groupby(enumerate(data), lambda (i,x):i-x):
... print map(operator.itemgetter(1), g)
...
[1]
[4, 5, 6]
[10]
[15, 16, 17, 18]
[22]
[25, 26, 27, 28]
>>> def take(n, seq):
... return list(islice(seq, n))
......
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