Changeset 391 for python/trunk/Doc/library/itertools.rst
- Timestamp:
- Mar 19, 2014, 11:31:01 PM (11 years ago)
- Location:
- python/trunk
- Files:
-
- 2 edited
Legend:
- Unmodified
- Added
- Removed
-
python/trunk
-
Property svn:mergeinfo
set to
/python/vendor/Python-2.7.6 merged eligible /python/vendor/current merged eligible
-
Property svn:mergeinfo
set to
-
python/trunk/Doc/library/itertools.rst
r2 r391 39 39 Iterator Arguments Results Example 40 40 ================== ================= ================================================= ========================================= 41 :func:`count` start start, start+1, start+2, ...``count(10) --> 10 11 12 13 14 ...``41 :func:`count` start, [step] start, start+step, start+2*step, ... ``count(10) --> 10 11 12 13 14 ...`` 42 42 :func:`cycle` p p0, p1, ... plast, p0, p1, ... ``cycle('ABCD') --> A B C D A B C D ...`` 43 43 :func:`repeat` elem [,n] elem, elem, elem, ... endlessly or up to n times ``repeat(10, 3) --> 10 10 10`` … … 50 50 ==================== ============================ ================================================= ============================================================= 51 51 :func:`chain` p, q, ... p0, p1, ... plast, q0, q1, ... ``chain('ABC', 'DEF') --> A B C D E F`` 52 :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`` 52 53 :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`` 53 54 :func:`groupby` iterable[, keyfunc] sub-iterators grouped by value of keyfunc(v) … … 71 72 :func:`permutations` p[, r] r-length tuples, all possible orderings, no repeated elements 72 73 :func:`combinations` p, r r-length tuples, in sorted order, no repeated elements 73 | 74 :func:`combinations_with_replacement` p, r r-length tuples, in sorted order, with repeated elements 74 75 ``product('ABCD', repeat=2)`` ``AA AB AC AD BA BB BC BD CA CB CC CD DA DB DC DD`` 75 76 ``permutations('ABCD', 2)`` ``AB AC AD BA BC BD CA CB CD DA DB DC`` 76 77 ``combinations('ABCD', 2)`` ``AB AC AD BC BD CD`` 78 ``combinations_with_replacement('ABCD', 2)`` ``AA AB AC AD BB BC BD CC CD DD`` 77 79 ============================================== ==================== ============================================================= 78 80 … … 102 104 103 105 104 .. function:: itertools.chain.from_iterable(iterable)106 .. classmethod:: chain.from_iterable(iterable) 105 107 106 108 Alternate constructor for :func:`chain`. Gets chained inputs from a 107 single iterable argument that is evaluated lazily. Equivalent to:: 108 109 @classmethod 109 single iterable argument that is evaluated lazily. Roughly equivalent to:: 110 110 111 def from_iterable(iterables): 111 112 # chain.from_iterable(['ABC', 'DEF']) --> A B C D E F … … 167 168 .. versionadded:: 2.6 168 169 169 .. function:: count([n]) 170 171 Make an iterator that returns consecutive integers starting with *n*. If not 172 specified *n* defaults to zero. Often used as an argument to :func:`imap` to 173 generate consecutive data points. Also, used with :func:`izip` to add sequence 174 numbers. Equivalent to:: 175 176 def count(n=0): 170 .. function:: combinations_with_replacement(iterable, r) 171 172 Return *r* length subsequences of elements from the input *iterable* 173 allowing individual elements to be repeated more than once. 174 175 Combinations are emitted in lexicographic sort order. So, if the 176 input *iterable* is sorted, the combination tuples will be produced 177 in sorted order. 178 179 Elements are treated as unique based on their position, not on their 180 value. So if the input elements are unique, the generated combinations 181 will also be unique. 182 183 Equivalent to:: 184 185 def combinations_with_replacement(iterable, r): 186 # combinations_with_replacement('ABC', 2) --> AA AB AC BB BC CC 187 pool = tuple(iterable) 188 n = len(pool) 189 if not n and r: 190 return 191 indices = [0] * r 192 yield tuple(pool[i] for i in indices) 193 while True: 194 for i in reversed(range(r)): 195 if indices[i] != n - 1: 196 break 197 else: 198 return 199 indices[i:] = [indices[i] + 1] * (r - i) 200 yield tuple(pool[i] for i in indices) 201 202 The code for :func:`combinations_with_replacement` can be also expressed as 203 a subsequence of :func:`product` after filtering entries where the elements 204 are not in sorted order (according to their position in the input pool):: 205 206 def combinations_with_replacement(iterable, r): 207 pool = tuple(iterable) 208 n = len(pool) 209 for indices in product(range(n), repeat=r): 210 if sorted(indices) == list(indices): 211 yield tuple(pool[i] for i in indices) 212 213 The number of items returned is ``(n+r-1)! / r! / (n-1)!`` when ``n > 0``. 214 215 .. versionadded:: 2.7 216 217 .. function:: compress(data, selectors) 218 219 Make an iterator that filters elements from *data* returning only those that 220 have a corresponding element in *selectors* that evaluates to ``True``. 221 Stops when either the *data* or *selectors* iterables has been exhausted. 222 Equivalent to:: 223 224 def compress(data, selectors): 225 # compress('ABCDEF', [1,0,1,0,1,1]) --> A C E F 226 return (d for d, s in izip(data, selectors) if s) 227 228 .. versionadded:: 2.7 229 230 231 .. function:: count(start=0, step=1) 232 233 Make an iterator that returns evenly spaced values starting with *n*. Often 234 used as an argument to :func:`imap` to generate consecutive data points. 235 Also, used with :func:`izip` to add sequence numbers. Equivalent to:: 236 237 def count(start=0, step=1): 177 238 # count(10) --> 10 11 12 13 14 ... 239 # count(2.5, 0.5) -> 2.5 3.0 3.5 ... 240 n = start 178 241 while True: 179 242 yield n 180 n += 1 181 243 n += step 244 245 When counting with floating point numbers, better accuracy can sometimes be 246 achieved by substituting multiplicative code such as: ``(start + step * i 247 for i in count())``. 248 249 .. versionchanged:: 2.7 250 added *step* argument and allowed non-integer arguments. 182 251 183 252 .. function:: cycle(iterable) … … 324 393 325 394 326 .. function:: islice(iterable, [start,] stop [, step]) 395 .. function:: islice(iterable, stop) 396 islice(iterable, start, stop[, step]) 327 397 328 398 Make an iterator that returns selected elements from the iterable. If *start* is … … 364 434 def izip(*iterables): 365 435 # izip('ABCD', 'xy') --> Ax By 366 itera bles = map(iter, iterables)367 while itera bles:368 yield tuple(map(next, itera bles))436 iterators = map(iter, iterables) 437 while iterators: 438 yield tuple(map(next, iterators)) 369 439 370 440 .. versionchanged:: 2.4 … … 387 457 Iteration continues until the longest iterable is exhausted. Equivalent to:: 388 458 459 class ZipExhausted(Exception): 460 pass 461 389 462 def izip_longest(*args, **kwds): 390 463 # izip_longest('ABCD', 'xy', fillvalue='-') --> Ax By C- D- 391 464 fillvalue = kwds.get('fillvalue') 392 def sentinel(counter = ([fillvalue]*(len(args)-1)).pop): 393 yield counter() # yields the fillvalue, or raises IndexError 465 counter = [len(args) - 1] 466 def sentinel(): 467 if not counter[0]: 468 raise ZipExhausted 469 counter[0] -= 1 470 yield fillvalue 394 471 fillers = repeat(fillvalue) 395 iter s = [chain(it, sentinel(), fillers) for it in args]472 iterators = [chain(it, sentinel(), fillers) for it in args] 396 473 try: 397 for tup in izip(*iters):398 yield tup 399 except IndexError:474 while iterators: 475 yield tuple(map(next, iterators)) 476 except ZipExhausted: 400 477 pass 401 478 … … 514 591 yield object 515 592 593 A common use for *repeat* is to supply a stream of constant values to *imap* 594 or *zip*:: 595 596 >>> list(imap(pow, xrange(10), repeat(2))) 597 [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] 516 598 517 599 .. function:: starmap(function, iterable) … … 574 656 575 657 576 .. _itertools-example:577 578 Examples579 --------580 581 The following examples show common uses for each tool and demonstrate ways they582 can be combined.583 584 .. doctest::585 586 >>> # Show a dictionary sorted and grouped by value587 >>> from operator import itemgetter588 >>> d = dict(a=1, b=2, c=1, d=2, e=1, f=2, g=3)589 >>> di = sorted(d.iteritems(), key=itemgetter(1))590 >>> for k, g in groupby(di, key=itemgetter(1)):591 ... print k, map(itemgetter(0), g)592 ...593 1 ['a', 'c', 'e']594 2 ['b', 'd', 'f']595 3 ['g']596 597 >>> # Find runs of consecutive numbers using groupby. The key to the solution598 >>> # is differencing with a range so that consecutive numbers all appear in599 >>> # same group.600 >>> data = [ 1, 4,5,6, 10, 15,16,17,18, 22, 25,26,27,28]601 >>> for k, g in groupby(enumerate(data), lambda (i,x):i-x):602 ... print map(itemgetter(1), g)603 ...604 [1]605 [4, 5, 6]606 [10]607 [15, 16, 17, 18]608 [22]609 [25, 26, 27, 28]610 611 612 613 658 .. _itertools-recipes: 614 659 … … 633 678 return list(islice(iterable, n)) 634 679 635 def enumerate(iterable, start=0):636 return izip(count(start), iterable)637 638 680 def tabulate(function, start=0): 639 681 "Return function(0), function(1), ..." … … 642 684 def consume(iterator, n): 643 685 "Advance the iterator n-steps ahead. If n is none, consume entirely." 644 # The technique uses objects that consume iterators at C speed.686 # Use functions that consume iterators at C speed. 645 687 if n is None: 646 688 # feed the entire iterator into a zero-length deque 647 689 collections.deque(iterator, maxlen=0) 648 690 else: 649 # advance to the em tpy slice starting at position n691 # advance to the empty slice starting at position n 650 692 next(islice(iterator, n, n), None) 651 693 … … 667 709 def ncycles(iterable, n): 668 710 "Returns the sequence elements n times" 669 return chain.from_iterable(repeat( iterable, n))711 return chain.from_iterable(repeat(tuple(iterable), n)) 670 712 671 713 def dotproduct(vec1, vec2): … … 673 715 674 716 def flatten(listOfLists): 675 return list(chain.from_iterable(listOfLists)) 717 "Flatten one level of nesting" 718 return chain.from_iterable(listOfLists) 676 719 677 720 def repeatfunc(func, times=None, *args): … … 690 733 return izip(a, b) 691 734 692 def grouper(n, iterable, fillvalue=None): 693 "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx" 735 def grouper(iterable, n, fillvalue=None): 736 "Collect data into fixed-length chunks or blocks" 737 # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx 694 738 args = [iter(iterable)] * n 695 739 return izip_longest(fillvalue=fillvalue, *args) … … 708 752 nexts = cycle(islice(nexts, pending)) 709 753 710 def compress(data, selectors):711 "compress('ABCDEF', [1,0,1,0,1,1]) --> A C E F"712 return (d for d, s in izip(data, selectors) if s)713 714 def combinations_with_replacement(iterable, r):715 "combinations_with_replacement('ABC', 2) --> AA AB AC BB BC CC"716 # number items returned: (n+r-1)! / r! / (n-1)!717 pool = tuple(iterable)718 n = len(pool)719 if not n and r:720 return721 indices = [0] * r722 yield tuple(pool[i] for i in indices)723 while True:724 for i in reversed(range(r)):725 if indices[i] != n - 1:726 break727 else:728 return729 indices[i:] = [indices[i] + 1] * (r - i)730 yield tuple(pool[i] for i in indices)731 732 754 def powerset(iterable): 733 755 "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)" … … 742 764 seen_add = seen.add 743 765 if key is None: 744 for element in iterable: 745 if element not in seen: 746 seen_add(element) 747 yield element 766 for element in ifilterfalse(seen.__contains__, iterable): 767 seen_add(element) 768 yield element 748 769 else: 749 770 for element in iterable: … … 759 780 return imap(next, imap(itemgetter(1), groupby(iterable, key))) 760 781 782 def iter_except(func, exception, first=None): 783 """ Call a function repeatedly until an exception is raised. 784 785 Converts a call-until-exception interface to an iterator interface. 786 Like __builtin__.iter(func, sentinel) but uses an exception instead 787 of a sentinel to end the loop. 788 789 Examples: 790 bsddbiter = iter_except(db.next, bsddb.error, db.first) 791 heapiter = iter_except(functools.partial(heappop, h), IndexError) 792 dictiter = iter_except(d.popitem, KeyError) 793 dequeiter = iter_except(d.popleft, IndexError) 794 queueiter = iter_except(q.get_nowait, Queue.Empty) 795 setiter = iter_except(s.pop, KeyError) 796 797 """ 798 try: 799 if first is not None: 800 yield first() 801 while 1: 802 yield func() 803 except exception: 804 pass 805 806 def random_product(*args, **kwds): 807 "Random selection from itertools.product(*args, **kwds)" 808 pools = map(tuple, args) * kwds.get('repeat', 1) 809 return tuple(random.choice(pool) for pool in pools) 810 811 def random_permutation(iterable, r=None): 812 "Random selection from itertools.permutations(iterable, r)" 813 pool = tuple(iterable) 814 r = len(pool) if r is None else r 815 return tuple(random.sample(pool, r)) 816 817 def random_combination(iterable, r): 818 "Random selection from itertools.combinations(iterable, r)" 819 pool = tuple(iterable) 820 n = len(pool) 821 indices = sorted(random.sample(xrange(n), r)) 822 return tuple(pool[i] for i in indices) 823 824 def random_combination_with_replacement(iterable, r): 825 "Random selection from itertools.combinations_with_replacement(iterable, r)" 826 pool = tuple(iterable) 827 n = len(pool) 828 indices = sorted(random.randrange(n) for i in xrange(r)) 829 return tuple(pool[i] for i in indices) 830 831 def tee_lookahead(t, i): 832 """Inspect the i-th upcomping value from a tee object 833 while leaving the tee object at its current position. 834 835 Raise an IndexError if the underlying iterator doesn't 836 have enough values. 837 838 """ 839 for value in islice(t.__copy__(), i, None): 840 return value 841 raise IndexError(i) 842 761 843 Note, many of the above recipes can be optimized by replacing global lookups 762 844 with local variables defined as default values. For example, the
Note:
See TracChangeset
for help on using the changeset viewer.