]> granicus.if.org Git - python/commitdiff
Add a Guido inspired example for groupby().
authorRaymond Hettinger <python@rcn.com>
Tue, 20 Jan 2004 20:04:40 +0000 (20:04 +0000)
committerRaymond Hettinger <python@rcn.com>
Tue, 20 Jan 2004 20:04:40 +0000 (20:04 +0000)
Doc/lib/libitertools.tex
Lib/test/test_itertools.py

index 51570ee60e5198bb5651cf5136f9ecda5083b97d..d07ef2b41b209163e6e80be0a71eef64e7086593 100644 (file)
@@ -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}
index 31b1b7c208c36971aaaa0f691fd643a320f69cfc..fe49f7521d499c139d8278b18a8648699da45058 100644 (file)
@@ -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))