Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1 | :mod:`itertools` --- Functions creating iterators for efficient looping |
| 2 | ======================================================================= |
| 3 | |
| 4 | .. module:: itertools |
| 5 | :synopsis: Functions creating iterators for efficient looping. |
| 6 | .. moduleauthor:: Raymond Hettinger <python@rcn.com> |
| 7 | .. sectionauthor:: Raymond Hettinger <python@rcn.com> |
| 8 | |
| 9 | |
Christian Heimes | fe337bf | 2008-03-23 21:54:12 +0000 | [diff] [blame] | 10 | .. testsetup:: |
| 11 | |
| 12 | from itertools import * |
| 13 | |
| 14 | |
Raymond Hettinger | f76b920 | 2009-02-17 20:00:59 +0000 | [diff] [blame] | 15 | This module implements a number of :term:`iterator` building blocks inspired |
| 16 | by constructs from APL, Haskell, and SML. Each has been recast in a form |
| 17 | suitable for Python. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 18 | |
| 19 | The module standardizes a core set of fast, memory efficient tools that are |
Raymond Hettinger | f76b920 | 2009-02-17 20:00:59 +0000 | [diff] [blame] | 20 | useful by themselves or in combination. Together, they form an "iterator |
| 21 | algebra" making it possible to construct specialized tools succinctly and |
| 22 | efficiently in pure Python. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 23 | |
| 24 | For instance, SML provides a tabulation tool: ``tabulate(f)`` which produces a |
Raymond Hettinger | a6c6037 | 2008-03-13 01:26:19 +0000 | [diff] [blame] | 25 | sequence ``f(0), f(1), ...``. But, this effect can be achieved in Python |
| 26 | by combining :func:`map` and :func:`count` to form ``map(f, count())``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 27 | |
Raymond Hettinger | 2c109ab | 2009-03-12 00:29:44 +0000 | [diff] [blame] | 28 | These tools and their built-in counterparts also work well with the high-speed |
| 29 | functions in the :mod:`operator` module. For example, the multiplication |
| 30 | operator can be mapped across two vectors to form an efficient dot-product: |
| 31 | ``sum(map(operator.mul, vector1, vector2))``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 32 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 33 | |
Raymond Hettinger | f76b920 | 2009-02-17 20:00:59 +0000 | [diff] [blame] | 34 | **Infinite Iterators:** |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 35 | |
Raymond Hettinger | 5bfd8ce | 2009-04-10 19:02:36 +0000 | [diff] [blame] | 36 | ================== ================= ================================================= ========================================= |
| 37 | Iterator Arguments Results Example |
| 38 | ================== ================= ================================================= ========================================= |
| 39 | :func:`count` start, [step] start, start+step, start+2*step, ... ``count(10) --> 10 11 12 13 14 ...`` |
| 40 | :func:`cycle` p p0, p1, ... plast, p0, p1, ... ``cycle('ABCD') --> A B C D A B C D ...`` |
| 41 | :func:`repeat` elem [,n] elem, elem, elem, ... endlessly or up to n times ``repeat(10, 3) --> 10 10 10`` |
| 42 | ================== ================= ================================================= ========================================= |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 43 | |
Raymond Hettinger | f76b920 | 2009-02-17 20:00:59 +0000 | [diff] [blame] | 44 | **Iterators terminating on the shortest input sequence:** |
| 45 | |
Raymond Hettinger | 5bfd8ce | 2009-04-10 19:02:36 +0000 | [diff] [blame] | 46 | ==================== ============================ ================================================= ============================================================= |
| 47 | Iterator Arguments Results Example |
| 48 | ==================== ============================ ================================================= ============================================================= |
| 49 | :func:`chain` p, q, ... p0, p1, ... plast, q0, q1, ... ``chain('ABC', 'DEF') --> A B C D E F`` |
| 50 | :func:`compress` data, selectors (d[0] if s[0]), (d[1] if s[1]), ... ``compress('ABCDEF', [1,0,1,0,1,1]) --> A C E F`` |
| 51 | :func:`dropwhile` pred, seq seq[n], seq[n+1], starting when pred fails ``dropwhile(lambda x: x<5, [1,4,6,4,1]) --> 6 4 1`` |
| 52 | :func:`filterfalse` pred, seq elements of seq where pred(elem) is False ``ifilterfalse(lambda x: x%2, range(10)) --> 0 2 4 6 8`` |
| 53 | :func:`groupby` iterable[, keyfunc] sub-iterators grouped by value of keyfunc(v) |
| 54 | :func:`islice` seq, [start,] stop [, step] elements from seq[start:stop:step] ``islice('ABCDEFG', 2, None) --> C D E F G`` |
| 55 | :func:`starmap` func, seq func(\*seq[0]), func(\*seq[1]), ... ``starmap(pow, [(2,5), (3,2), (10,3)]) --> 32 9 1000`` |
| 56 | :func:`takewhile` pred, seq seq[0], seq[1], until pred fails ``takewhile(lambda x: x<5, [1,4,6,4,1]) --> 1 4`` |
| 57 | :func:`tee` it, n it1, it2 , ... itn splits one iterator into n |
| 58 | :func:`zip_longest` p, q, ... (p[0], q[0]), (p[1], q[1]), ... ``izip_longest('ABCD', 'xy', fillvalue='-') --> Ax By C- D-`` |
| 59 | ==================== ============================ ================================================= ============================================================= |
Raymond Hettinger | f76b920 | 2009-02-17 20:00:59 +0000 | [diff] [blame] | 60 | |
| 61 | **Combinatoric generators:** |
| 62 | |
Raymond Hettinger | 7f587cd | 2009-04-10 19:43:50 +0000 | [diff] [blame] | 63 | ============================================== ==================== ============================================================= |
| 64 | Iterator Arguments Results |
| 65 | ============================================== ==================== ============================================================= |
| 66 | :func:`product` p, q, ... [repeat=1] cartesian product, equivalent to a nested for-loop |
| 67 | :func:`permutations` p[, r] r-length tuples, all possible orderings, no repeated elements |
| 68 | :func:`combinations` p[, r] r-length tuples, in sorted order, no repeated elements |
| 69 | :func:`combinations_with_replacement` p[, r] r-length tuples, in sorted order, with repeated elements |
| 70 | | |
| 71 | ``product('ABCD', repeat=2)`` ``AA AB AC AD BA BB BC BD CA CB CC CD DA DB DC DD`` |
| 72 | ``permutations('ABCD', 2)`` ``AB AC AD BA BC BD CA CB CD DA DB DC`` |
| 73 | ``combinations('ABCD', 2)`` ``AB AC AD BC BD CD`` |
| 74 | ``combinations_with_replacement('ABCD', 2)`` ``AA AB AC AD BB BC BD CC CD DD`` |
| 75 | ============================================== ==================== ============================================================= |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 76 | |
| 77 | |
| 78 | .. _itertools-functions: |
| 79 | |
| 80 | Itertool functions |
| 81 | ------------------ |
| 82 | |
| 83 | The following module functions all construct and return iterators. Some provide |
| 84 | streams of infinite length, so they should only be accessed by functions or |
| 85 | loops that truncate the stream. |
| 86 | |
| 87 | |
| 88 | .. function:: chain(*iterables) |
| 89 | |
| 90 | Make an iterator that returns elements from the first iterable until it is |
| 91 | exhausted, then proceeds to the next iterable, until all of the iterables are |
| 92 | exhausted. Used for treating consecutive sequences as a single sequence. |
| 93 | Equivalent to:: |
| 94 | |
| 95 | def chain(*iterables): |
Raymond Hettinger | dd1150e | 2008-03-13 02:39:40 +0000 | [diff] [blame] | 96 | # chain('ABC', 'DEF') --> A B C D E F |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 97 | for it in iterables: |
| 98 | for element in it: |
| 99 | yield element |
| 100 | |
| 101 | |
Christian Heimes | 70e7ea2 | 2008-02-28 20:02:27 +0000 | [diff] [blame] | 102 | .. function:: itertools.chain.from_iterable(iterable) |
| 103 | |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 104 | Alternate constructor for :func:`chain`. Gets chained inputs from a |
Christian Heimes | 70e7ea2 | 2008-02-28 20:02:27 +0000 | [diff] [blame] | 105 | single iterable argument that is evaluated lazily. Equivalent to:: |
| 106 | |
| 107 | @classmethod |
| 108 | def from_iterable(iterables): |
Raymond Hettinger | dd1150e | 2008-03-13 02:39:40 +0000 | [diff] [blame] | 109 | # chain.from_iterable(['ABC', 'DEF']) --> A B C D E F |
Christian Heimes | 70e7ea2 | 2008-02-28 20:02:27 +0000 | [diff] [blame] | 110 | for it in iterables: |
| 111 | for element in it: |
| 112 | yield element |
| 113 | |
Christian Heimes | 7864476 | 2008-03-04 23:39:23 +0000 | [diff] [blame] | 114 | |
Christian Heimes | 836baa5 | 2008-02-26 08:18:30 +0000 | [diff] [blame] | 115 | .. function:: combinations(iterable, r) |
| 116 | |
Christian Heimes | dae2a89 | 2008-04-19 00:55:37 +0000 | [diff] [blame] | 117 | Return *r* length subsequences of elements from the input *iterable*. |
Christian Heimes | 836baa5 | 2008-02-26 08:18:30 +0000 | [diff] [blame] | 118 | |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 119 | Combinations are emitted in lexicographic sort order. So, if the |
Christian Heimes | 836baa5 | 2008-02-26 08:18:30 +0000 | [diff] [blame] | 120 | input *iterable* is sorted, the combination tuples will be produced |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 121 | in sorted order. |
Christian Heimes | 836baa5 | 2008-02-26 08:18:30 +0000 | [diff] [blame] | 122 | |
| 123 | Elements are treated as unique based on their position, not on their |
| 124 | value. So if the input elements are unique, there will be no repeat |
Christian Heimes | 70e7ea2 | 2008-02-28 20:02:27 +0000 | [diff] [blame] | 125 | values in each combination. |
Christian Heimes | 836baa5 | 2008-02-26 08:18:30 +0000 | [diff] [blame] | 126 | |
Christian Heimes | 836baa5 | 2008-02-26 08:18:30 +0000 | [diff] [blame] | 127 | Equivalent to:: |
| 128 | |
| 129 | def combinations(iterable, r): |
Raymond Hettinger | dd1150e | 2008-03-13 02:39:40 +0000 | [diff] [blame] | 130 | # combinations('ABCD', 2) --> AB AC AD BC BD CD |
| 131 | # combinations(range(4), 3) --> 012 013 023 123 |
Christian Heimes | 836baa5 | 2008-02-26 08:18:30 +0000 | [diff] [blame] | 132 | pool = tuple(iterable) |
Christian Heimes | 380f7f2 | 2008-02-28 11:19:05 +0000 | [diff] [blame] | 133 | n = len(pool) |
Raymond Hettinger | 5bad41e | 2009-01-08 21:01:54 +0000 | [diff] [blame] | 134 | if r > n: |
| 135 | return |
| 136 | indices = list(range(r)) |
Christian Heimes | b558a2e | 2008-03-02 22:46:37 +0000 | [diff] [blame] | 137 | yield tuple(pool[i] for i in indices) |
Raymond Hettinger | cf984ce | 2009-02-18 20:56:51 +0000 | [diff] [blame] | 138 | while True: |
Christian Heimes | 380f7f2 | 2008-02-28 11:19:05 +0000 | [diff] [blame] | 139 | for i in reversed(range(r)): |
Christian Heimes | b558a2e | 2008-03-02 22:46:37 +0000 | [diff] [blame] | 140 | if indices[i] != i + n - r: |
Christian Heimes | 836baa5 | 2008-02-26 08:18:30 +0000 | [diff] [blame] | 141 | break |
Christian Heimes | 380f7f2 | 2008-02-28 11:19:05 +0000 | [diff] [blame] | 142 | else: |
| 143 | return |
Christian Heimes | b558a2e | 2008-03-02 22:46:37 +0000 | [diff] [blame] | 144 | indices[i] += 1 |
Christian Heimes | 380f7f2 | 2008-02-28 11:19:05 +0000 | [diff] [blame] | 145 | for j in range(i+1, r): |
Christian Heimes | b558a2e | 2008-03-02 22:46:37 +0000 | [diff] [blame] | 146 | indices[j] = indices[j-1] + 1 |
| 147 | yield tuple(pool[i] for i in indices) |
Christian Heimes | 836baa5 | 2008-02-26 08:18:30 +0000 | [diff] [blame] | 148 | |
Christian Heimes | 7864476 | 2008-03-04 23:39:23 +0000 | [diff] [blame] | 149 | The code for :func:`combinations` can be also expressed as a subsequence |
| 150 | of :func:`permutations` after filtering entries where the elements are not |
| 151 | in sorted order (according to their position in the input pool):: |
| 152 | |
| 153 | def combinations(iterable, r): |
| 154 | pool = tuple(iterable) |
| 155 | n = len(pool) |
| 156 | for indices in permutations(range(n), r): |
| 157 | if sorted(indices) == list(indices): |
| 158 | yield tuple(pool[i] for i in indices) |
| 159 | |
Raymond Hettinger | 5bad41e | 2009-01-08 21:01:54 +0000 | [diff] [blame] | 160 | The number of items returned is ``n! / r! / (n-r)!`` when ``0 <= r <= n`` |
| 161 | or zero when ``r > n``. |
Christian Heimes | 836baa5 | 2008-02-26 08:18:30 +0000 | [diff] [blame] | 162 | |
Raymond Hettinger | d07d939 | 2009-01-27 04:20:44 +0000 | [diff] [blame] | 163 | .. function:: combinations_with_replacement(iterable, r) |
| 164 | |
| 165 | Return *r* length subsequences of elements from the input *iterable* |
| 166 | allowing individual elements to be repeated more than once. |
| 167 | |
| 168 | Combinations are emitted in lexicographic sort order. So, if the |
| 169 | input *iterable* is sorted, the combination tuples will be produced |
| 170 | in sorted order. |
| 171 | |
| 172 | Elements are treated as unique based on their position, not on their |
| 173 | value. So if the input elements are unique, the generated combinations |
| 174 | will also be unique. |
| 175 | |
| 176 | Equivalent to:: |
| 177 | |
| 178 | def combinations_with_replacement(iterable, r): |
| 179 | # combinations_with_replacement('ABC', 2) --> AA AB AC BB BC CC |
| 180 | pool = tuple(iterable) |
| 181 | n = len(pool) |
| 182 | if not n and r: |
| 183 | return |
| 184 | indices = [0] * r |
| 185 | yield tuple(pool[i] for i in indices) |
Raymond Hettinger | cf984ce | 2009-02-18 20:56:51 +0000 | [diff] [blame] | 186 | while True: |
Raymond Hettinger | d07d939 | 2009-01-27 04:20:44 +0000 | [diff] [blame] | 187 | for i in reversed(range(r)): |
| 188 | if indices[i] != n - 1: |
| 189 | break |
| 190 | else: |
| 191 | return |
| 192 | indices[i:] = [indices[i] + 1] * (r - i) |
| 193 | yield tuple(pool[i] for i in indices) |
| 194 | |
| 195 | The code for :func:`combinations_with_replacement` can be also expressed as |
| 196 | a subsequence of :func:`product` after filtering entries where the elements |
| 197 | are not in sorted order (according to their position in the input pool):: |
| 198 | |
| 199 | def combinations_with_replacement(iterable, r): |
| 200 | pool = tuple(iterable) |
| 201 | n = len(pool) |
| 202 | for indices in product(range(n), repeat=r): |
| 203 | if sorted(indices) == list(indices): |
| 204 | yield tuple(pool[i] for i in indices) |
| 205 | |
| 206 | The number of items returned is ``(n+r-1)! / r! / (n-1)!`` when ``n > 0``. |
| 207 | |
Raymond Hettinger | 3072921 | 2009-02-12 06:28:27 +0000 | [diff] [blame] | 208 | .. versionadded:: 3.1 |
Raymond Hettinger | d07d939 | 2009-01-27 04:20:44 +0000 | [diff] [blame] | 209 | |
Raymond Hettinger | 6b3b0fc | 2009-01-26 02:56:58 +0000 | [diff] [blame] | 210 | .. function:: compress(data, selectors) |
| 211 | |
| 212 | Make an iterator that filters elements from *data* returning only those that |
| 213 | have a corresponding element in *selectors* that evaluates to ``True``. |
Benjamin Peterson | d23f822 | 2009-04-05 19:13:16 +0000 | [diff] [blame] | 214 | Stops when either the *data* or *selectors* iterables has been exhausted. |
Raymond Hettinger | 6b3b0fc | 2009-01-26 02:56:58 +0000 | [diff] [blame] | 215 | Equivalent to:: |
| 216 | |
| 217 | def compress(data, selectors): |
| 218 | # compress('ABCDEF', [1,0,1,0,1,1]) --> A C E F |
| 219 | return (d for d, s in zip(data, selectors) if s) |
| 220 | |
Raymond Hettinger | 3072921 | 2009-02-12 06:28:27 +0000 | [diff] [blame] | 221 | .. versionadded:: 3.1 |
Raymond Hettinger | 6b3b0fc | 2009-01-26 02:56:58 +0000 | [diff] [blame] | 222 | |
| 223 | |
Raymond Hettinger | 9e8dbbc | 2009-02-14 04:21:49 +0000 | [diff] [blame] | 224 | .. function:: count(start=0, step=1) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 225 | |
Raymond Hettinger | 3072921 | 2009-02-12 06:28:27 +0000 | [diff] [blame] | 226 | Make an iterator that returns evenly spaced values starting with *n*. Often |
| 227 | used as an argument to :func:`map` to generate consecutive data points. |
| 228 | Also, used with :func:`zip` to add sequence numbers. Equivalent to:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 229 | |
Raymond Hettinger | 9e8dbbc | 2009-02-14 04:21:49 +0000 | [diff] [blame] | 230 | def count(start=0, step=1): |
Raymond Hettinger | dd1150e | 2008-03-13 02:39:40 +0000 | [diff] [blame] | 231 | # count(10) --> 10 11 12 13 14 ... |
Raymond Hettinger | 3072921 | 2009-02-12 06:28:27 +0000 | [diff] [blame] | 232 | # count(2.5, 0.5) -> 3.5 3.0 4.5 ... |
Raymond Hettinger | 9e8dbbc | 2009-02-14 04:21:49 +0000 | [diff] [blame] | 233 | n = start |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 234 | while True: |
| 235 | yield n |
Raymond Hettinger | 3072921 | 2009-02-12 06:28:27 +0000 | [diff] [blame] | 236 | n += step |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 237 | |
Raymond Hettinger | 3072921 | 2009-02-12 06:28:27 +0000 | [diff] [blame] | 238 | .. versionchanged:: 3.1 |
| 239 | added *step* argument and allowed non-integer arguments. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 240 | |
| 241 | .. function:: cycle(iterable) |
| 242 | |
| 243 | Make an iterator returning elements from the iterable and saving a copy of each. |
| 244 | When the iterable is exhausted, return elements from the saved copy. Repeats |
| 245 | indefinitely. Equivalent to:: |
| 246 | |
| 247 | def cycle(iterable): |
Raymond Hettinger | dd1150e | 2008-03-13 02:39:40 +0000 | [diff] [blame] | 248 | # cycle('ABCD') --> A B C D A B C D A B C D ... |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 249 | saved = [] |
| 250 | for element in iterable: |
| 251 | yield element |
| 252 | saved.append(element) |
| 253 | while saved: |
| 254 | for element in saved: |
| 255 | yield element |
| 256 | |
| 257 | Note, this member of the toolkit may require significant auxiliary storage |
| 258 | (depending on the length of the iterable). |
| 259 | |
| 260 | |
| 261 | .. function:: dropwhile(predicate, iterable) |
| 262 | |
| 263 | Make an iterator that drops elements from the iterable as long as the predicate |
| 264 | is true; afterwards, returns every element. Note, the iterator does not produce |
| 265 | *any* output until the predicate first becomes false, so it may have a lengthy |
| 266 | start-up time. Equivalent to:: |
| 267 | |
| 268 | def dropwhile(predicate, iterable): |
Raymond Hettinger | dd1150e | 2008-03-13 02:39:40 +0000 | [diff] [blame] | 269 | # dropwhile(lambda x: x<5, [1,4,6,4,1]) --> 6 4 1 |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 270 | iterable = iter(iterable) |
| 271 | for x in iterable: |
| 272 | if not predicate(x): |
| 273 | yield x |
| 274 | break |
| 275 | for x in iterable: |
| 276 | yield x |
| 277 | |
Raymond Hettinger | 749761e | 2009-01-27 04:42:48 +0000 | [diff] [blame] | 278 | .. function:: filterfalse(predicate, iterable) |
| 279 | |
| 280 | Make an iterator that filters elements from iterable returning only those for |
| 281 | which the predicate is ``False``. If *predicate* is ``None``, return the items |
| 282 | that are false. Equivalent to:: |
| 283 | |
| 284 | def filterfalse(predicate, iterable): |
| 285 | # filterfalse(lambda x: x%2, range(10)) --> 0 2 4 6 8 |
| 286 | if predicate is None: |
| 287 | predicate = bool |
| 288 | for x in iterable: |
| 289 | if not predicate(x): |
| 290 | yield x |
| 291 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 292 | |
Georg Brandl | 3dd3388 | 2009-06-01 17:35:27 +0000 | [diff] [blame] | 293 | .. function:: groupby(iterable, key=None) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 294 | |
| 295 | Make an iterator that returns consecutive keys and groups from the *iterable*. |
| 296 | The *key* is a function computing a key value for each element. If not |
| 297 | specified or is ``None``, *key* defaults to an identity function and returns |
| 298 | the element unchanged. Generally, the iterable needs to already be sorted on |
| 299 | the same key function. |
| 300 | |
| 301 | The operation of :func:`groupby` is similar to the ``uniq`` filter in Unix. It |
| 302 | generates a break or new group every time the value of the key function changes |
| 303 | (which is why it is usually necessary to have sorted the data using the same key |
| 304 | function). That behavior differs from SQL's GROUP BY which aggregates common |
| 305 | elements regardless of their input order. |
| 306 | |
| 307 | The returned group is itself an iterator that shares the underlying iterable |
| 308 | with :func:`groupby`. Because the source is shared, when the :func:`groupby` |
| 309 | object is advanced, the previous group is no longer visible. So, if that data |
| 310 | is needed later, it should be stored as a list:: |
| 311 | |
| 312 | groups = [] |
| 313 | uniquekeys = [] |
| 314 | data = sorted(data, key=keyfunc) |
| 315 | for k, g in groupby(data, keyfunc): |
| 316 | groups.append(list(g)) # Store group iterator as a list |
| 317 | uniquekeys.append(k) |
| 318 | |
| 319 | :func:`groupby` is equivalent to:: |
| 320 | |
| 321 | class groupby(object): |
Raymond Hettinger | dd1150e | 2008-03-13 02:39:40 +0000 | [diff] [blame] | 322 | # [k for k, g in groupby('AAAABBBCCDAABBB')] --> A B C D A B |
Raymond Hettinger | d04fa31 | 2009-02-04 19:45:13 +0000 | [diff] [blame] | 323 | # [list(g) for k, g in groupby('AAAABBBCCD')] --> AAAA BBB CC D |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 324 | def __init__(self, iterable, key=None): |
| 325 | if key is None: |
| 326 | key = lambda x: x |
| 327 | self.keyfunc = key |
| 328 | self.it = iter(iterable) |
Christian Heimes | 5b5e81c | 2007-12-31 16:14:33 +0000 | [diff] [blame] | 329 | self.tgtkey = self.currkey = self.currvalue = object() |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 330 | def __iter__(self): |
| 331 | return self |
| 332 | def __next__(self): |
| 333 | while self.currkey == self.tgtkey: |
Raymond Hettinger | 21315ba | 2009-02-23 19:38:09 +0000 | [diff] [blame] | 334 | self.currvalue = next(self.it) # Exit on StopIteration |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 335 | self.currkey = self.keyfunc(self.currvalue) |
| 336 | self.tgtkey = self.currkey |
| 337 | return (self.currkey, self._grouper(self.tgtkey)) |
| 338 | def _grouper(self, tgtkey): |
| 339 | while self.currkey == tgtkey: |
| 340 | yield self.currvalue |
Raymond Hettinger | 21315ba | 2009-02-23 19:38:09 +0000 | [diff] [blame] | 341 | self.currvalue = next(self.it) # Exit on StopIteration |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 342 | self.currkey = self.keyfunc(self.currvalue) |
| 343 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 344 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 345 | .. function:: islice(iterable, [start,] stop [, step]) |
| 346 | |
| 347 | Make an iterator that returns selected elements from the iterable. If *start* is |
| 348 | non-zero, then elements from the iterable are skipped until start is reached. |
| 349 | Afterward, elements are returned consecutively unless *step* is set higher than |
| 350 | one which results in items being skipped. If *stop* is ``None``, then iteration |
| 351 | continues until the iterator is exhausted, if at all; otherwise, it stops at the |
| 352 | specified position. Unlike regular slicing, :func:`islice` does not support |
| 353 | negative values for *start*, *stop*, or *step*. Can be used to extract related |
| 354 | fields from data where the internal structure has been flattened (for example, a |
| 355 | multi-line report may list a name field on every third line). Equivalent to:: |
| 356 | |
| 357 | def islice(iterable, *args): |
Raymond Hettinger | dd1150e | 2008-03-13 02:39:40 +0000 | [diff] [blame] | 358 | # islice('ABCDEFG', 2) --> A B |
| 359 | # islice('ABCDEFG', 2, 4) --> C D |
| 360 | # islice('ABCDEFG', 2, None) --> C D E F G |
| 361 | # islice('ABCDEFG', 0, None, 2) --> A C E G |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 362 | s = slice(*args) |
Raymond Hettinger | 7c8494b | 2009-05-14 21:48:02 +0000 | [diff] [blame] | 363 | it = iter(range(s.start or 0, s.stop or sys.maxsize, s.step or 1)) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 364 | nexti = next(it) |
| 365 | for i, element in enumerate(iterable): |
| 366 | if i == nexti: |
| 367 | yield element |
| 368 | nexti = next(it) |
| 369 | |
| 370 | If *start* is ``None``, then iteration starts at zero. If *step* is ``None``, |
| 371 | then the step defaults to one. |
| 372 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 373 | |
Georg Brandl | 3dd3388 | 2009-06-01 17:35:27 +0000 | [diff] [blame] | 374 | .. function:: permutations(iterable, r=None) |
Christian Heimes | 70e7ea2 | 2008-02-28 20:02:27 +0000 | [diff] [blame] | 375 | |
| 376 | Return successive *r* length permutations of elements in the *iterable*. |
| 377 | |
| 378 | If *r* is not specified or is ``None``, then *r* defaults to the length |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 379 | of the *iterable* and all possible full-length permutations |
Christian Heimes | 70e7ea2 | 2008-02-28 20:02:27 +0000 | [diff] [blame] | 380 | are generated. |
| 381 | |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 382 | Permutations are emitted in lexicographic sort order. So, if the |
Christian Heimes | 70e7ea2 | 2008-02-28 20:02:27 +0000 | [diff] [blame] | 383 | input *iterable* is sorted, the permutation tuples will be produced |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 384 | in sorted order. |
Christian Heimes | 70e7ea2 | 2008-02-28 20:02:27 +0000 | [diff] [blame] | 385 | |
| 386 | Elements are treated as unique based on their position, not on their |
| 387 | value. So if the input elements are unique, there will be no repeat |
| 388 | values in each permutation. |
| 389 | |
Christian Heimes | b558a2e | 2008-03-02 22:46:37 +0000 | [diff] [blame] | 390 | Equivalent to:: |
| 391 | |
| 392 | def permutations(iterable, r=None): |
Raymond Hettinger | dd1150e | 2008-03-13 02:39:40 +0000 | [diff] [blame] | 393 | # permutations('ABCD', 2) --> AB AC AD BA BC BD CA CB CD DA DB DC |
| 394 | # permutations(range(3)) --> 012 021 102 120 201 210 |
Christian Heimes | b558a2e | 2008-03-02 22:46:37 +0000 | [diff] [blame] | 395 | pool = tuple(iterable) |
| 396 | n = len(pool) |
| 397 | r = n if r is None else r |
Raymond Hettinger | 5bad41e | 2009-01-08 21:01:54 +0000 | [diff] [blame] | 398 | if r > n: |
| 399 | return |
| 400 | indices = list(range(n)) |
Christian Heimes | fe337bf | 2008-03-23 21:54:12 +0000 | [diff] [blame] | 401 | cycles = range(n, n-r, -1) |
Christian Heimes | b558a2e | 2008-03-02 22:46:37 +0000 | [diff] [blame] | 402 | yield tuple(pool[i] for i in indices[:r]) |
| 403 | while n: |
| 404 | for i in reversed(range(r)): |
| 405 | cycles[i] -= 1 |
| 406 | if cycles[i] == 0: |
| 407 | indices[i:] = indices[i+1:] + indices[i:i+1] |
| 408 | cycles[i] = n - i |
| 409 | else: |
| 410 | j = cycles[i] |
| 411 | indices[i], indices[-j] = indices[-j], indices[i] |
| 412 | yield tuple(pool[i] for i in indices[:r]) |
| 413 | break |
| 414 | else: |
| 415 | return |
Christian Heimes | 70e7ea2 | 2008-02-28 20:02:27 +0000 | [diff] [blame] | 416 | |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 417 | The code for :func:`permutations` can be also expressed as a subsequence of |
Christian Heimes | 7864476 | 2008-03-04 23:39:23 +0000 | [diff] [blame] | 418 | :func:`product`, filtered to exclude entries with repeated elements (those |
| 419 | from the same position in the input pool):: |
| 420 | |
| 421 | def permutations(iterable, r=None): |
| 422 | pool = tuple(iterable) |
| 423 | n = len(pool) |
| 424 | r = n if r is None else r |
| 425 | for indices in product(range(n), repeat=r): |
| 426 | if len(set(indices)) == r: |
| 427 | yield tuple(pool[i] for i in indices) |
| 428 | |
Raymond Hettinger | 5bad41e | 2009-01-08 21:01:54 +0000 | [diff] [blame] | 429 | The number of items returned is ``n! / (n-r)!`` when ``0 <= r <= n`` |
| 430 | or zero when ``r > n``. |
Christian Heimes | 70e7ea2 | 2008-02-28 20:02:27 +0000 | [diff] [blame] | 431 | |
Georg Brandl | 3dd3388 | 2009-06-01 17:35:27 +0000 | [diff] [blame] | 432 | .. function:: product(*iterables, repeat=1) |
Christian Heimes | 90c3d9b | 2008-02-23 13:18:03 +0000 | [diff] [blame] | 433 | |
| 434 | Cartesian product of input iterables. |
| 435 | |
| 436 | Equivalent to nested for-loops in a generator expression. For example, |
| 437 | ``product(A, B)`` returns the same as ``((x,y) for x in A for y in B)``. |
| 438 | |
Christian Heimes | dae2a89 | 2008-04-19 00:55:37 +0000 | [diff] [blame] | 439 | The nested loops cycle like an odometer with the rightmost element advancing |
| 440 | on every iteration. This pattern creates a lexicographic ordering so that if |
| 441 | the input's iterables are sorted, the product tuples are emitted in sorted |
| 442 | order. |
Christian Heimes | 90c3d9b | 2008-02-23 13:18:03 +0000 | [diff] [blame] | 443 | |
Christian Heimes | 9e7f1d2 | 2008-02-28 12:27:11 +0000 | [diff] [blame] | 444 | To compute the product of an iterable with itself, specify the number of |
| 445 | repetitions with the optional *repeat* keyword argument. For example, |
| 446 | ``product(A, repeat=4)`` means the same as ``product(A, A, A, A)``. |
| 447 | |
Christian Heimes | 7864476 | 2008-03-04 23:39:23 +0000 | [diff] [blame] | 448 | This function is equivalent to the following code, except that the |
| 449 | actual implementation does not build up intermediate results in memory:: |
Christian Heimes | 90c3d9b | 2008-02-23 13:18:03 +0000 | [diff] [blame] | 450 | |
Raymond Hettinger | a137e1f | 2008-03-13 02:43:14 +0000 | [diff] [blame] | 451 | def product(*args, repeat=1): |
Raymond Hettinger | dd1150e | 2008-03-13 02:39:40 +0000 | [diff] [blame] | 452 | # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy |
| 453 | # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111 |
Raymond Hettinger | a137e1f | 2008-03-13 02:43:14 +0000 | [diff] [blame] | 454 | pools = map(tuple, args) * repeat |
Christian Heimes | 7864476 | 2008-03-04 23:39:23 +0000 | [diff] [blame] | 455 | result = [[]] |
| 456 | for pool in pools: |
| 457 | result = [x+[y] for x in result for y in pool] |
| 458 | for prod in result: |
| 459 | yield tuple(prod) |
Christian Heimes | 90c3d9b | 2008-02-23 13:18:03 +0000 | [diff] [blame] | 460 | |
| 461 | |
Raymond Hettinger | d75ad44 | 2009-06-01 19:16:52 +0000 | [diff] [blame^] | 462 | .. function:: repeat(object[, times]) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 463 | |
| 464 | Make an iterator that returns *object* over and over again. Runs indefinitely |
Raymond Hettinger | a6c6037 | 2008-03-13 01:26:19 +0000 | [diff] [blame] | 465 | unless the *times* argument is specified. Used as argument to :func:`map` for |
Raymond Hettinger | dd1150e | 2008-03-13 02:39:40 +0000 | [diff] [blame] | 466 | invariant parameters to the called function. Also used with :func:`zip` to |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 467 | create an invariant part of a tuple record. Equivalent to:: |
| 468 | |
| 469 | def repeat(object, times=None): |
Raymond Hettinger | dd1150e | 2008-03-13 02:39:40 +0000 | [diff] [blame] | 470 | # repeat(10, 3) --> 10 10 10 |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 471 | if times is None: |
| 472 | while True: |
| 473 | yield object |
| 474 | else: |
| 475 | for i in range(times): |
| 476 | yield object |
| 477 | |
| 478 | |
| 479 | .. function:: starmap(function, iterable) |
| 480 | |
Christian Heimes | 679db4a | 2008-01-18 09:56:22 +0000 | [diff] [blame] | 481 | Make an iterator that computes the function using arguments obtained from |
Raymond Hettinger | a6c6037 | 2008-03-13 01:26:19 +0000 | [diff] [blame] | 482 | the iterable. Used instead of :func:`map` when argument parameters are already |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 483 | grouped in tuples from a single iterable (the data has been "pre-zipped"). The |
Raymond Hettinger | a6c6037 | 2008-03-13 01:26:19 +0000 | [diff] [blame] | 484 | difference between :func:`map` and :func:`starmap` parallels the distinction |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 485 | between ``function(a,b)`` and ``function(*c)``. Equivalent to:: |
| 486 | |
| 487 | def starmap(function, iterable): |
Raymond Hettinger | dd1150e | 2008-03-13 02:39:40 +0000 | [diff] [blame] | 488 | # starmap(pow, [(2,5), (3,2), (10,3)]) --> 32 9 1000 |
Christian Heimes | 679db4a | 2008-01-18 09:56:22 +0000 | [diff] [blame] | 489 | for args in iterable: |
| 490 | yield function(*args) |
| 491 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 492 | |
| 493 | .. function:: takewhile(predicate, iterable) |
| 494 | |
| 495 | Make an iterator that returns elements from the iterable as long as the |
| 496 | predicate is true. Equivalent to:: |
| 497 | |
| 498 | def takewhile(predicate, iterable): |
Raymond Hettinger | dd1150e | 2008-03-13 02:39:40 +0000 | [diff] [blame] | 499 | # takewhile(lambda x: x<5, [1,4,6,4,1]) --> 1 4 |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 500 | for x in iterable: |
| 501 | if predicate(x): |
| 502 | yield x |
| 503 | else: |
| 504 | break |
| 505 | |
| 506 | |
Georg Brandl | 3dd3388 | 2009-06-01 17:35:27 +0000 | [diff] [blame] | 507 | .. function:: tee(iterable, n=2) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 508 | |
Raymond Hettinger | cf984ce | 2009-02-18 20:56:51 +0000 | [diff] [blame] | 509 | Return *n* independent iterators from a single iterable. Equivalent to:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 510 | |
Raymond Hettinger | cf984ce | 2009-02-18 20:56:51 +0000 | [diff] [blame] | 511 | def tee(iterable, n=2): |
| 512 | it = iter(iterable) |
| 513 | deques = [collections.deque() for i in range(n)] |
| 514 | def gen(mydeque): |
| 515 | while True: |
| 516 | if not mydeque: # when the local deque is empty |
| 517 | newval = next(it) # fetch a new value and |
| 518 | for d in deques: # load it to all the deques |
| 519 | d.append(newval) |
| 520 | yield mydeque.popleft() |
| 521 | return tuple(gen(d) for d in deques) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 522 | |
Raymond Hettinger | cf984ce | 2009-02-18 20:56:51 +0000 | [diff] [blame] | 523 | Once :func:`tee` has made a split, the original *iterable* should not be |
| 524 | used anywhere else; otherwise, the *iterable* could get advanced without |
| 525 | the tee objects being informed. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 526 | |
Raymond Hettinger | cf984ce | 2009-02-18 20:56:51 +0000 | [diff] [blame] | 527 | This itertool may require significant auxiliary storage (depending on how |
| 528 | much temporary data needs to be stored). In general, if one iterator uses |
| 529 | most or all of the data before another iterator starts, it is faster to use |
| 530 | :func:`list` instead of :func:`tee`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 531 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 532 | |
Georg Brandl | 3dd3388 | 2009-06-01 17:35:27 +0000 | [diff] [blame] | 533 | .. function:: zip_longest(*iterables, fillvalue=None) |
Raymond Hettinger | 749761e | 2009-01-27 04:42:48 +0000 | [diff] [blame] | 534 | |
| 535 | Make an iterator that aggregates elements from each of the iterables. If the |
| 536 | iterables are of uneven length, missing values are filled-in with *fillvalue*. |
| 537 | Iteration continues until the longest iterable is exhausted. Equivalent to:: |
| 538 | |
| 539 | def zip_longest(*args, fillvalue=None): |
| 540 | # zip_longest('ABCD', 'xy', fillvalue='-') --> Ax By C- D- |
| 541 | def sentinel(counter = ([fillvalue]*(len(args)-1)).pop): |
| 542 | yield counter() # yields the fillvalue, or raises IndexError |
| 543 | fillers = repeat(fillvalue) |
| 544 | iters = [chain(it, sentinel(), fillers) for it in args] |
| 545 | try: |
| 546 | for tup in zip(*iters): |
| 547 | yield tup |
| 548 | except IndexError: |
| 549 | pass |
| 550 | |
| 551 | If one of the iterables is potentially infinite, then the :func:`zip_longest` |
| 552 | function should be wrapped with something that limits the number of calls |
| 553 | (for example :func:`islice` or :func:`takewhile`). If not specified, |
| 554 | *fillvalue* defaults to ``None``. |
| 555 | |
| 556 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 557 | .. _itertools-recipes: |
| 558 | |
| 559 | Recipes |
| 560 | ------- |
| 561 | |
| 562 | This section shows recipes for creating an extended toolset using the existing |
| 563 | itertools as building blocks. |
| 564 | |
| 565 | The extended tools offer the same high performance as the underlying toolset. |
| 566 | The superior memory performance is kept by processing elements one at a time |
| 567 | rather than bringing the whole iterable into memory all at once. Code volume is |
| 568 | kept small by linking the tools together in a functional style which helps |
| 569 | eliminate temporary variables. High speed is retained by preferring |
Georg Brandl | 9afde1c | 2007-11-01 20:32:30 +0000 | [diff] [blame] | 570 | "vectorized" building blocks over the use of for-loops and :term:`generator`\s |
Christian Heimes | fe337bf | 2008-03-23 21:54:12 +0000 | [diff] [blame] | 571 | which incur interpreter overhead. |
| 572 | |
| 573 | .. testcode:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 574 | |
Georg Brandl | 3dbca81 | 2008-07-23 16:10:53 +0000 | [diff] [blame] | 575 | def take(n, iterable): |
| 576 | "Return first n items of the iterable as a list" |
| 577 | return list(islice(iterable, n)) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 578 | |
Georg Brandl | 3dbca81 | 2008-07-23 16:10:53 +0000 | [diff] [blame] | 579 | def enumerate(iterable, start=0): |
| 580 | return zip(count(start), iterable) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 581 | |
Georg Brandl | 3dbca81 | 2008-07-23 16:10:53 +0000 | [diff] [blame] | 582 | def tabulate(function, start=0): |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 583 | "Return function(0), function(1), ..." |
Georg Brandl | 3dbca81 | 2008-07-23 16:10:53 +0000 | [diff] [blame] | 584 | return map(function, count(start)) |
Raymond Hettinger | dd1150e | 2008-03-13 02:39:40 +0000 | [diff] [blame] | 585 | |
Raymond Hettinger | fa00796 | 2009-03-09 11:55:25 +0000 | [diff] [blame] | 586 | def consume(iterator, n): |
| 587 | "Advance the iterator n-steps ahead. If n is none, consume entirely." |
| 588 | collections.deque(islice(iterator, n), maxlen=0) |
| 589 | |
Raymond Hettinger | cdf8ba3 | 2009-02-19 04:45:07 +0000 | [diff] [blame] | 590 | def nth(iterable, n, default=None): |
| 591 | "Returns the nth item or a default value" |
| 592 | return next(islice(iterable, n, None), default) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 593 | |
Georg Brandl | 3dbca81 | 2008-07-23 16:10:53 +0000 | [diff] [blame] | 594 | def quantify(iterable, pred=bool): |
| 595 | "Count how many times the predicate is true" |
| 596 | return sum(map(pred, iterable)) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 597 | |
Georg Brandl | 3dbca81 | 2008-07-23 16:10:53 +0000 | [diff] [blame] | 598 | def padnone(iterable): |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 599 | """Returns the sequence elements and then returns None indefinitely. |
| 600 | |
| 601 | Useful for emulating the behavior of the built-in map() function. |
| 602 | """ |
Georg Brandl | 3dbca81 | 2008-07-23 16:10:53 +0000 | [diff] [blame] | 603 | return chain(iterable, repeat(None)) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 604 | |
Georg Brandl | 3dbca81 | 2008-07-23 16:10:53 +0000 | [diff] [blame] | 605 | def ncycles(iterable, n): |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 606 | "Returns the sequence elements n times" |
Georg Brandl | 3dbca81 | 2008-07-23 16:10:53 +0000 | [diff] [blame] | 607 | return chain.from_iterable(repeat(iterable, n)) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 608 | |
| 609 | def dotproduct(vec1, vec2): |
Raymond Hettinger | a6c6037 | 2008-03-13 01:26:19 +0000 | [diff] [blame] | 610 | return sum(map(operator.mul, vec1, vec2)) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 611 | |
| 612 | def flatten(listOfLists): |
Christian Heimes | 70e7ea2 | 2008-02-28 20:02:27 +0000 | [diff] [blame] | 613 | return list(chain.from_iterable(listOfLists)) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 614 | |
| 615 | def repeatfunc(func, times=None, *args): |
| 616 | """Repeat calls to func with specified arguments. |
| 617 | |
| 618 | Example: repeatfunc(random.random) |
| 619 | """ |
| 620 | if times is None: |
| 621 | return starmap(func, repeat(args)) |
Christian Heimes | 70e7ea2 | 2008-02-28 20:02:27 +0000 | [diff] [blame] | 622 | return starmap(func, repeat(args, times)) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 623 | |
| 624 | def pairwise(iterable): |
| 625 | "s -> (s0,s1), (s1,s2), (s2, s3), ..." |
| 626 | a, b = tee(iterable) |
Raymond Hettinger | 21315ba | 2009-02-23 19:38:09 +0000 | [diff] [blame] | 627 | next(b, None) |
Raymond Hettinger | dd1150e | 2008-03-13 02:39:40 +0000 | [diff] [blame] | 628 | return zip(a, b) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 629 | |
Raymond Hettinger | dd1150e | 2008-03-13 02:39:40 +0000 | [diff] [blame] | 630 | def grouper(n, iterable, fillvalue=None): |
Raymond Hettinger | f5a2e47 | 2008-07-30 07:37:37 +0000 | [diff] [blame] | 631 | "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx" |
Raymond Hettinger | dd1150e | 2008-03-13 02:39:40 +0000 | [diff] [blame] | 632 | args = [iter(iterable)] * n |
Raymond Hettinger | 883d276 | 2009-01-27 04:57:51 +0000 | [diff] [blame] | 633 | return zip_longest(*args, fillvalue=fillvalue) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 634 | |
Christian Heimes | 7b3ce6a | 2008-01-31 14:31:45 +0000 | [diff] [blame] | 635 | def roundrobin(*iterables): |
Raymond Hettinger | f5a2e47 | 2008-07-30 07:37:37 +0000 | [diff] [blame] | 636 | "roundrobin('ABC', 'D', 'EF') --> A D E B F C" |
Christian Heimes | 70e7ea2 | 2008-02-28 20:02:27 +0000 | [diff] [blame] | 637 | # Recipe credited to George Sakkis |
Christian Heimes | 7b3ce6a | 2008-01-31 14:31:45 +0000 | [diff] [blame] | 638 | pending = len(iterables) |
Raymond Hettinger | dd1150e | 2008-03-13 02:39:40 +0000 | [diff] [blame] | 639 | nexts = cycle(iter(it).__next__ for it in iterables) |
Christian Heimes | 7b3ce6a | 2008-01-31 14:31:45 +0000 | [diff] [blame] | 640 | while pending: |
| 641 | try: |
| 642 | for next in nexts: |
| 643 | yield next() |
| 644 | except StopIteration: |
| 645 | pending -= 1 |
| 646 | nexts = cycle(islice(nexts, pending)) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 647 | |
Christian Heimes | 90c3d9b | 2008-02-23 13:18:03 +0000 | [diff] [blame] | 648 | def powerset(iterable): |
Raymond Hettinger | ace6733 | 2009-01-26 02:23:50 +0000 | [diff] [blame] | 649 | "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)" |
| 650 | s = list(iterable) |
| 651 | return chain.from_iterable(combinations(s, r) for r in range(len(s)+1)) |
Christian Heimes | 90c3d9b | 2008-02-23 13:18:03 +0000 | [diff] [blame] | 652 | |
Raymond Hettinger | fd88ea7 | 2009-03-23 22:42:28 +0000 | [diff] [blame] | 653 | def unique_everseen(iterable, key=None): |
| 654 | "List unique elements, preserving order. Remember all elements ever seen." |
| 655 | # unique_everseen('AAAABBBCCDAABBB') --> A B C D |
| 656 | # unique_everseen('ABBCcAD', str.lower) --> A B C D |
| 657 | seen = set() |
| 658 | seen_add = seen.add |
| 659 | if key is None: |
| 660 | for element in iterable: |
| 661 | if element not in seen: |
| 662 | seen_add(element) |
| 663 | yield element |
| 664 | else: |
| 665 | for element in iterable: |
| 666 | k = key(element) |
| 667 | if k not in seen: |
| 668 | seen_add(k) |
| 669 | yield element |
Raymond Hettinger | ad9d96b | 2009-01-02 21:39:07 +0000 | [diff] [blame] | 670 | |
Raymond Hettinger | fd88ea7 | 2009-03-23 22:42:28 +0000 | [diff] [blame] | 671 | def unique_justseen(iterable, key=None): |
| 672 | "List unique elements, preserving order. Remember only the element just seen." |
| 673 | # unique_justseen('AAAABBBCCDAABBB') --> A B C D A B |
| 674 | # unique_justseen('ABBCcAD', str.lower) --> A B C A D |
| 675 | return map(next, map(itemgetter(1), groupby(iterable, key))) |