Movatterモバイル変換


[0]ホーム

URL:


Navigation

10.1.itertools — Functions creating iterators for efficient looping

This module implements a number ofiterator building blocks inspiredby constructs from APL, Haskell, and SML. Each has been recast in a formsuitable for Python.

The module standardizes a core set of fast, memory efficient tools that areuseful by themselves or in combination. Together, they form an “iteratoralgebra” making it possible to construct specialized tools succinctly andefficiently in pure Python.

For instance, SML provides a tabulation tool:tabulate(f) which produces asequencef(0),f(1),.... The same effect can be achieved in Pythonby combiningmap() andcount() to formmap(f,count()).

These tools and their built-in counterparts also work well with the high-speedfunctions in theoperator module. For example, the multiplicationoperator can be mapped across two vectors to form an efficient dot-product:sum(map(operator.mul,vector1,vector2)).

Infinite Iterators:

IteratorArgumentsResultsExample
count()start, [step]start, start+step, start+2*step, ...count(10)-->1011121314...
cycle()pp0, p1, ... plast, p0, p1, ...cycle('ABCD')-->ABCDABCD...
repeat()elem [,n]elem, elem, elem, ... endlessly or up to n timesrepeat(10,3)-->101010

Iterators terminating on the shortest input sequence:

IteratorArgumentsResultsExample
accumulate()p [,func]p0, p0+p1, p0+p1+p2, ...accumulate([1,2,3,4,5])-->1361015
chain()p, q, ...p0, p1, ... plast, q0, q1, ...chain('ABC','DEF')-->ABCDEF
chain.from_iterable()iterablep0, p1, ... plast, q0, q1, ...chain.from_iterable(['ABC','DEF'])-->ABCDEF
compress()data, selectors(d[0] if s[0]), (d[1] if s[1]), ...compress('ABCDEF',[1,0,1,0,1,1])-->ACEF
dropwhile()pred, seqseq[n], seq[n+1], starting when pred failsdropwhile(lambdax:x<5,[1,4,6,4,1])-->641
filterfalse()pred, seqelements of seq where pred(elem) is falsefilterfalse(lambdax:x%2,range(10))-->02468
groupby()iterable[, keyfunc]sub-iterators grouped by value of keyfunc(v) 
islice()seq, [start,] stop [, step]elements from seq[start:stop:step]islice('ABCDEFG',2,None)-->CDEFG
starmap()func, seqfunc(*seq[0]), func(*seq[1]), ...starmap(pow,[(2,5),(3,2),(10,3)])-->3291000
takewhile()pred, seqseq[0], seq[1], until pred failstakewhile(lambdax:x<5,[1,4,6,4,1])-->14
tee()it, nit1, it2, ... itn splits one iterator into n 
zip_longest()p, q, ...(p[0], q[0]), (p[1], q[1]), ...zip_longest('ABCD','xy',fillvalue='-')-->AxByC-D-

Combinatoric generators:

IteratorArgumentsResults
product()p, q, ... [repeat=1]cartesian product, equivalent to a nested for-loop
permutations()p[, r]r-length tuples, all possible orderings, no repeated elements
combinations()p, rr-length tuples, in sorted order, no repeated elements
combinations_with_replacement()p, rr-length tuples, in sorted order, with repeated elements
product('ABCD',repeat=2) AAABACADBABBBCBDCACBCCCDDADBDCDD
permutations('ABCD',2) ABACADBABCBDCACBCDDADBDC
combinations('ABCD',2) ABACADBCBDCD
combinations_with_replacement('ABCD',2) AAABACADBBBCBDCCCDDD

10.1.1. Itertool functions

The following module functions all construct and return iterators. Some providestreams of infinite length, so they should only be accessed by functions orloops that truncate the stream.

itertools.accumulate(iterable[,func])

Make an iterator that returns accumulated sums. Elements may be any addabletype includingDecimal orFraction.If the optionalfunc argument is supplied, it should be a function of twoarguments and it will be used instead of addition.

Equivalent to:

defaccumulate(iterable,func=operator.add):'Return running totals'# accumulate([1,2,3,4,5]) --> 1 3 6 10 15# accumulate([1,2,3,4,5], operator.mul) --> 1 2 6 24 120it=iter(iterable)total=next(it)yieldtotalforelementinit:total=func(total,element)yieldtotal

There are a number of uses for thefunc argument. It can be set tomin() for a running minimum,max() for a running maximum, oroperator.mul() for a running product. Amortization tables can bebuilt by accumulating interest and applying payments. First-orderrecurrence relationscan be modeled by supplying the initial value in the iterable and using onlythe accumulated total infunc argument:

>>>data=[3,4,6,2,1,9,0,7,5,8]>>>list(accumulate(data,operator.mul))# running product[3, 12, 72, 144, 144, 1296, 0, 0, 0, 0]>>>list(accumulate(data,max))# running maximum[3, 4, 6, 6, 6, 9, 9, 9, 9, 9]# Amortize a 5% loan of 1000 with 4 annual payments of 90>>>cashflows=[1000,-90,-90,-90,-90]>>>list(accumulate(cashflows,lambdabal,pmt:bal*1.05+pmt))[1000, 960.0, 918.0, 873.9000000000001, 827.5950000000001]# Chaotic recurrence relation http://en.wikipedia.org/wiki/Logistic_map>>>logistic_map=lambdax,_:r*x*(1-x)>>>r=3.8>>>x0=0.4>>>inputs=repeat(x0,36)# only the initial value is used>>>[format(x,'.2f')forxinaccumulate(inputs,logistic_map)]['0.40', '0.91', '0.30', '0.81', '0.60', '0.92', '0.29', '0.79', '0.63', '0.88', '0.39', '0.90', '0.33', '0.84', '0.52', '0.95', '0.18', '0.57', '0.93', '0.25', '0.71', '0.79', '0.63', '0.88', '0.39', '0.91', '0.32', '0.83', '0.54', '0.95', '0.20', '0.60', '0.91', '0.30', '0.80', '0.60']

Seefunctools.reduce() for a similar function that returns only thefinal accumulated value.

New in version 3.2.

Changed in version 3.3:Added the optionalfunc parameter.

itertools.chain(*iterables)

Make an iterator that returns elements from the first iterable until it isexhausted, then proceeds to the next iterable, until all of the iterables areexhausted. Used for treating consecutive sequences as a single sequence.Equivalent to:

defchain(*iterables):# chain('ABC', 'DEF') --> A B C D E Fforitiniterables:forelementinit:yieldelement
classmethodchain.from_iterable(iterable)

Alternate constructor forchain(). Gets chained inputs from asingle iterable argument that is evaluated lazily. Roughly equivalent to:

deffrom_iterable(iterables):# chain.from_iterable(['ABC', 'DEF']) --> A B C D E Fforitiniterables:forelementinit:yieldelement
itertools.combinations(iterable,r)

Returnr length subsequences of elements from the inputiterable.

Combinations are emitted in lexicographic sort order. So, if theinputiterable is sorted, the combination tuples will be producedin sorted order.

Elements are treated as unique based on their position, not on theirvalue. So if the input elements are unique, there will be no repeatvalues in each combination.

Equivalent to:

defcombinations(iterable,r):# combinations('ABCD', 2) --> AB AC AD BC BD CD# combinations(range(4), 3) --> 012 013 023 123pool=tuple(iterable)n=len(pool)ifr>n:returnindices=list(range(r))yieldtuple(pool[i]foriinindices)whileTrue:foriinreversed(range(r)):ifindices[i]!=i+n-r:breakelse:returnindices[i]+=1forjinrange(i+1,r):indices[j]=indices[j-1]+1yieldtuple(pool[i]foriinindices)

The code forcombinations() can be also expressed as a subsequenceofpermutations() after filtering entries where the elements are notin sorted order (according to their position in the input pool):

defcombinations(iterable,r):pool=tuple(iterable)n=len(pool)forindicesinpermutations(range(n),r):ifsorted(indices)==list(indices):yieldtuple(pool[i]foriinindices)

The number of items returned isn!/r!/(n-r)! when0<=r<=nor zero whenr>n.

itertools.combinations_with_replacement(iterable,r)

Returnr length subsequences of elements from the inputiterableallowing individual elements to be repeated more than once.

Combinations are emitted in lexicographic sort order. So, if theinputiterable is sorted, the combination tuples will be producedin sorted order.

Elements are treated as unique based on their position, not on theirvalue. So if the input elements are unique, the generated combinationswill also be unique.

Equivalent to:

defcombinations_with_replacement(iterable,r):# combinations_with_replacement('ABC', 2) --> AA AB AC BB BC CCpool=tuple(iterable)n=len(pool)ifnotnandr:returnindices=[0]*ryieldtuple(pool[i]foriinindices)whileTrue:foriinreversed(range(r)):ifindices[i]!=n-1:breakelse:returnindices[i:]=[indices[i]+1]*(r-i)yieldtuple(pool[i]foriinindices)

The code forcombinations_with_replacement() can be also expressed asa subsequence ofproduct() after filtering entries where the elementsare not in sorted order (according to their position in the input pool):

defcombinations_with_replacement(iterable,r):pool=tuple(iterable)n=len(pool)forindicesinproduct(range(n),repeat=r):ifsorted(indices)==list(indices):yieldtuple(pool[i]foriinindices)

The number of items returned is(n+r-1)!/r!/(n-1)! whenn>0.

New in version 3.1.

itertools.compress(data,selectors)

Make an iterator that filters elements fromdata returning only those thathave a corresponding element inselectors that evaluates toTrue.Stops when either thedata orselectors iterables has been exhausted.Equivalent to:

defcompress(data,selectors):# compress('ABCDEF', [1,0,1,0,1,1]) --> A C E Freturn(dford,sinzip(data,selectors)ifs)

New in version 3.1.

itertools.count(start=0,step=1)

Make an iterator that returns evenly spaced values starting with numberstart. Oftenused as an argument tomap() to generate consecutive data points.Also, used withzip() to add sequence numbers. Equivalent to:

defcount(start=0,step=1):# count(10) --> 10 11 12 13 14 ...# count(2.5, 0.5) -> 2.5 3.0 3.5 ...n=startwhileTrue:yieldnn+=step

When counting with floating point numbers, better accuracy can sometimes beachieved by substituting multiplicative code such as:(start+step*iforiincount()).

Changed in version 3.1:Addedstep argument and allowed non-integer arguments.

itertools.cycle(iterable)

Make an iterator returning elements from the iterable and saving a copy of each.When the iterable is exhausted, return elements from the saved copy. Repeatsindefinitely. Equivalent to:

defcycle(iterable):# cycle('ABCD') --> A B C D A B C D A B C D ...saved=[]forelementiniterable:yieldelementsaved.append(element)whilesaved:forelementinsaved:yieldelement

Note, this member of the toolkit may require significant auxiliary storage(depending on the length of the iterable).

itertools.dropwhile(predicate,iterable)

Make an iterator that drops elements from the iterable as long as the predicateis true; afterwards, returns every element. Note, the iterator does not produceany output until the predicate first becomes false, so it may have a lengthystart-up time. Equivalent to:

defdropwhile(predicate,iterable):# dropwhile(lambda x: x<5, [1,4,6,4,1]) --> 6 4 1iterable=iter(iterable)forxiniterable:ifnotpredicate(x):yieldxbreakforxiniterable:yieldx
itertools.filterfalse(predicate,iterable)

Make an iterator that filters elements from iterable returning only those forwhich the predicate isFalse. Ifpredicate isNone, return the itemsthat are false. Equivalent to:

deffilterfalse(predicate,iterable):# filterfalse(lambda x: x%2, range(10)) --> 0 2 4 6 8ifpredicateisNone:predicate=boolforxiniterable:ifnotpredicate(x):yieldx
itertools.groupby(iterable,key=None)

Make an iterator that returns consecutive keys and groups from theiterable.Thekey is a function computing a key value for each element. If notspecified or isNone,key defaults to an identity function and returnsthe element unchanged. Generally, the iterable needs to already be sorted onthe same key function.

The operation ofgroupby() is similar to theuniq filter in Unix. Itgenerates a break or new group every time the value of the key function changes(which is why it is usually necessary to have sorted the data using the same keyfunction). That behavior differs from SQL’s GROUP BY which aggregates commonelements regardless of their input order.

The returned group is itself an iterator that shares the underlying iterablewithgroupby(). Because the source is shared, when thegroupby()object is advanced, the previous group is no longer visible. So, if that datais needed later, it should be stored as a list:

groups=[]uniquekeys=[]data=sorted(data,key=keyfunc)fork,gingroupby(data,keyfunc):groups.append(list(g))# Store group iterator as a listuniquekeys.append(k)

groupby() is equivalent to:

classgroupby:# [k for k, g in groupby('AAAABBBCCDAABBB')] --> A B C D A B# [list(g) for k, g in groupby('AAAABBBCCD')] --> AAAA BBB CC Ddef__init__(self,iterable,key=None):ifkeyisNone:key=lambdax:xself.keyfunc=keyself.it=iter(iterable)self.tgtkey=self.currkey=self.currvalue=object()def__iter__(self):returnselfdef__next__(self):whileself.currkey==self.tgtkey:self.currvalue=next(self.it)# Exit on StopIterationself.currkey=self.keyfunc(self.currvalue)self.tgtkey=self.currkeyreturn(self.currkey,self._grouper(self.tgtkey))def_grouper(self,tgtkey):whileself.currkey==tgtkey:yieldself.currvalueself.currvalue=next(self.it)# Exit on StopIterationself.currkey=self.keyfunc(self.currvalue)
itertools.islice(iterable,stop)
itertools.islice(iterable,start,stop[,step])

Make an iterator that returns selected elements from the iterable. Ifstart isnon-zero, then elements from the iterable are skipped until start is reached.Afterward, elements are returned consecutively unlessstep is set higher thanone which results in items being skipped. Ifstop isNone, then iterationcontinues until the iterator is exhausted, if at all; otherwise, it stops at thespecified position. Unlike regular slicing,islice() does not supportnegative values forstart,stop, orstep. Can be used to extract relatedfields from data where the internal structure has been flattened (for example, amulti-line report may list a name field on every third line). Equivalent to:

defislice(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 Gs=slice(*args)it=iter(range(s.startor0,s.stoporsys.maxsize,s.stepor1))nexti=next(it)fori,elementinenumerate(iterable):ifi==nexti:yieldelementnexti=next(it)

Ifstart isNone, then iteration starts at zero. Ifstep isNone,then the step defaults to one.

itertools.permutations(iterable,r=None)

Return successiver length permutations of elements in theiterable.

Ifr is not specified or isNone, thenr defaults to the lengthof theiterable and all possible full-length permutationsare generated.

Permutations are emitted in lexicographic sort order. So, if theinputiterable is sorted, the permutation tuples will be producedin sorted order.

Elements are treated as unique based on their position, not on theirvalue. So if the input elements are unique, there will be no repeatvalues in each permutation.

Equivalent to:

defpermutations(iterable,r=None):# permutations('ABCD', 2) --> AB AC AD BA BC BD CA CB CD DA DB DC# permutations(range(3)) --> 012 021 102 120 201 210pool=tuple(iterable)n=len(pool)r=nifrisNoneelserifr>n:returnindices=list(range(n))cycles=list(range(n,n-r,-1))yieldtuple(pool[i]foriinindices[:r])whilen:foriinreversed(range(r)):cycles[i]-=1ifcycles[i]==0:indices[i:]=indices[i+1:]+indices[i:i+1]cycles[i]=n-ielse:j=cycles[i]indices[i],indices[-j]=indices[-j],indices[i]yieldtuple(pool[i]foriinindices[:r])breakelse:return

The code forpermutations() can be also expressed as a subsequence ofproduct(), filtered to exclude entries with repeated elements (thosefrom the same position in the input pool):

defpermutations(iterable,r=None):pool=tuple(iterable)n=len(pool)r=nifrisNoneelserforindicesinproduct(range(n),repeat=r):iflen(set(indices))==r:yieldtuple(pool[i]foriinindices)

The number of items returned isn!/(n-r)! when0<=r<=nor zero whenr>n.

itertools.product(*iterables,repeat=1)

Cartesian product of input iterables.

Equivalent to nested for-loops in a generator expression. For example,product(A,B) returns the same as((x,y)forxinAforyinB).

The nested loops cycle like an odometer with the rightmost element advancingon every iteration. This pattern creates a lexicographic ordering so that ifthe input’s iterables are sorted, the product tuples are emitted in sortedorder.

To compute the product of an iterable with itself, specify the number ofrepetitions with the optionalrepeat keyword argument. For example,product(A,repeat=4) means the same asproduct(A,A,A,A).

This function is equivalent to the following code, except that theactual implementation does not build up intermediate results in memory:

defproduct(*args,repeat=1):# product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy# product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111pools=[tuple(pool)forpoolinargs]*repeatresult=[[]]forpoolinpools:result=[x+[y]forxinresultforyinpool]forprodinresult:yieldtuple(prod)
itertools.repeat(object[,times])

Make an iterator that returnsobject over and over again. Runs indefinitelyunless thetimes argument is specified. Used as argument tomap() forinvariant parameters to the called function. Also used withzip() tocreate an invariant part of a tuple record. Equivalent to:

defrepeat(object,times=None):# repeat(10, 3) --> 10 10 10iftimesisNone:whileTrue:yieldobjectelse:foriinrange(times):yieldobject

A common use forrepeat is to supply a stream of constant values tomaporzip:

>>>list(map(pow,range(10),repeat(2)))[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
itertools.starmap(function,iterable)

Make an iterator that computes the function using arguments obtained fromthe iterable. Used instead ofmap() when argument parameters are alreadygrouped in tuples from a single iterable (the data has been “pre-zipped”). Thedifference betweenmap() andstarmap() parallels the distinctionbetweenfunction(a,b) andfunction(*c). Equivalent to:

defstarmap(function,iterable):# starmap(pow, [(2,5), (3,2), (10,3)]) --> 32 9 1000forargsiniterable:yieldfunction(*args)
itertools.takewhile(predicate,iterable)

Make an iterator that returns elements from the iterable as long as thepredicate is true. Equivalent to:

deftakewhile(predicate,iterable):# takewhile(lambda x: x<5, [1,4,6,4,1]) --> 1 4forxiniterable:ifpredicate(x):yieldxelse:break
itertools.tee(iterable,n=2)

Returnn independent iterators from a single iterable. Equivalent to:

deftee(iterable,n=2):it=iter(iterable)deques=[collections.deque()foriinrange(n)]defgen(mydeque):whileTrue:ifnotmydeque:# when the local deque is emptynewval=next(it)# fetch a new value andfordindeques:# load it to all the dequesd.append(newval)yieldmydeque.popleft()returntuple(gen(d)fordindeques)

Oncetee() has made a split, the originaliterable should not beused anywhere else; otherwise, theiterable could get advanced withoutthe tee objects being informed.

This itertool may require significant auxiliary storage (depending on howmuch temporary data needs to be stored). In general, if one iterator usesmost or all of the data before another iterator starts, it is faster to uselist() instead oftee().

itertools.zip_longest(*iterables,fillvalue=None)

Make an iterator that aggregates elements from each of the iterables. If theiterables are of uneven length, missing values are filled-in withfillvalue.Iteration continues until the longest iterable is exhausted. Equivalent to:

classZipExhausted(Exception):passdefzip_longest(*args,**kwds):# zip_longest('ABCD', 'xy', fillvalue='-') --> Ax By C- D-fillvalue=kwds.get('fillvalue')counter=len(args)-1defsentinel():nonlocalcounterifnotcounter:raiseZipExhaustedcounter-=1yieldfillvaluefillers=repeat(fillvalue)iterators=[chain(it,sentinel(),fillers)foritinargs]try:whileiterators:yieldtuple(map(next,iterators))exceptZipExhausted:pass

If one of the iterables is potentially infinite, then thezip_longest()function should be wrapped with something that limits the number of calls(for exampleislice() ortakewhile()). If not specified,fillvalue defaults toNone.

10.1.2. Itertools Recipes

This section shows recipes for creating an extended toolset using the existingitertools as building blocks.

The extended tools offer the same high performance as the underlying toolset.The superior memory performance is kept by processing elements one at a timerather than bringing the whole iterable into memory all at once. Code volume iskept small by linking the tools together in a functional style which helpseliminate temporary variables. High speed is retained by preferring“vectorized” building blocks over the use of for-loops andgeneratorswhich incur interpreter overhead.

deftake(n,iterable):"Return first n items of the iterable as a list"returnlist(islice(iterable,n))deftabulate(function,start=0):"Return function(0), function(1), ..."returnmap(function,count(start))defconsume(iterator,n):"Advance the iterator n-steps ahead. If n is none, consume entirely."# Use functions that consume iterators at C speed.ifnisNone:# feed the entire iterator into a zero-length dequecollections.deque(iterator,maxlen=0)else:# advance to the empty slice starting at position nnext(islice(iterator,n,n),None)defnth(iterable,n,default=None):"Returns the nth item or a default value"returnnext(islice(iterable,n,None),default)defquantify(iterable,pred=bool):"Count how many times the predicate is true"returnsum(map(pred,iterable))defpadnone(iterable):"""Returns the sequence elements and then returns None indefinitely.    Useful for emulating the behavior of the built-in map() function.    """returnchain(iterable,repeat(None))defncycles(iterable,n):"Returns the sequence elements n times"returnchain.from_iterable(repeat(tuple(iterable),n))defdotproduct(vec1,vec2):returnsum(map(operator.mul,vec1,vec2))defflatten(listOfLists):"Flatten one level of nesting"returnchain.from_iterable(listOfLists)defrepeatfunc(func,times=None,*args):"""Repeat calls to func with specified arguments.    Example:  repeatfunc(random.random)    """iftimesisNone:returnstarmap(func,repeat(args))returnstarmap(func,repeat(args,times))defpairwise(iterable):"s -> (s0,s1), (s1,s2), (s2, s3), ..."a,b=tee(iterable)next(b,None)returnzip(a,b)defgrouper(iterable,n,fillvalue=None):"Collect data into fixed-length chunks or blocks"# grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"args=[iter(iterable)]*nreturnzip_longest(*args,fillvalue=fillvalue)defroundrobin(*iterables):"roundrobin('ABC', 'D', 'EF') --> A D E B F C"# Recipe credited to George Sakkispending=len(iterables)nexts=cycle(iter(it).__next__foritiniterables)whilepending:try:fornextinnexts:yieldnext()exceptStopIteration:pending-=1nexts=cycle(islice(nexts,pending))defpartition(pred,iterable):'Use a predicate to partition entries into false entries and true entries'# partition(is_odd, range(10)) --> 0 2 4 6 8   and  1 3 5 7 9t1,t2=tee(iterable)returnfilterfalse(pred,t1),filter(pred,t2)defpowerset(iterable):"powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"s=list(iterable)returnchain.from_iterable(combinations(s,r)forrinrange(len(s)+1))defunique_everseen(iterable,key=None):"List unique elements, preserving order. Remember all elements ever seen."# unique_everseen('AAAABBBCCDAABBB') --> A B C D# unique_everseen('ABBCcAD', str.lower) --> A B C Dseen=set()seen_add=seen.addifkeyisNone:forelementinfilterfalse(seen.__contains__,iterable):seen_add(element)yieldelementelse:forelementiniterable:k=key(element)ifknotinseen:seen_add(k)yieldelementdefunique_justseen(iterable,key=None):"List unique elements, preserving order. Remember only the element just seen."# unique_justseen('AAAABBBCCDAABBB') --> A B C D A B# unique_justseen('ABBCcAD', str.lower) --> A B C A Dreturnmap(next,map(itemgetter(1),groupby(iterable,key)))defiter_except(func,exception,first=None):""" Call a function repeatedly until an exception is raised.    Converts a call-until-exception interface to an iterator interface.    Like builtins.iter(func, sentinel) but uses an exception instead    of a sentinel to end the loop.    Examples:        iter_except(functools.partial(heappop, h), IndexError)   # priority queue iterator        iter_except(d.popitem, KeyError)                         # non-blocking dict iterator        iter_except(d.popleft, IndexError)                       # non-blocking deque iterator        iter_except(q.get_nowait, Queue.Empty)                   # loop over a producer Queue        iter_except(s.pop, KeyError)                             # non-blocking set iterator    """try:iffirstisnotNone:yieldfirst()# For database APIs needing an initial cast to db.first()while1:yieldfunc()exceptexception:passdefrandom_product(*args,repeat=1):"Random selection from itertools.product(*args, **kwds)"pools=[tuple(pool)forpoolinargs]*repeatreturntuple(random.choice(pool)forpoolinpools)defrandom_permutation(iterable,r=None):"Random selection from itertools.permutations(iterable, r)"pool=tuple(iterable)r=len(pool)ifrisNoneelserreturntuple(random.sample(pool,r))defrandom_combination(iterable,r):"Random selection from itertools.combinations(iterable, r)"pool=tuple(iterable)n=len(pool)indices=sorted(random.sample(range(n),r))returntuple(pool[i]foriinindices)defrandom_combination_with_replacement(iterable,r):"Random selection from itertools.combinations_with_replacement(iterable, r)"pool=tuple(iterable)n=len(pool)indices=sorted(random.randrange(n)foriinrange(r))returntuple(pool[i]foriinindices)

Note, many of the above recipes can be optimized by replacing global lookupswith local variables defined as default values. For example, thedotproduct recipe can be written as:

defdotproduct(vec1,vec2,sum=sum,map=map,mul=operator.mul):returnsum(map(mul,vec1,vec2))

Table Of Contents

Previous topic

10. Functional Programming Modules

Next topic

10.2.functools — Higher-order functions and operations on callable objects

This Page

Quick search

Enter search terms or a module, class or function name.

Navigation

©Copyright 1990-2017, Python Software Foundation.
The Python Software Foundation is a non-profit corporation.Please donate.
Last updated on Sep 19, 2017.Found a bug?
Created usingSphinx 1.2.

[8]ページ先頭

©2009-2025 Movatter.jp