Python学习笔记combinationspermutationsproduct
联合企业
创建combinations(iterable, r)迭代器并返回iterable中长度为r的所有子序列。 返回的子序列中的项目按在iterable中输入的顺序进行:排序
http://www.Sina.com/: http://www.Sina.com /
返回由输入iterable中的元素组成的长度为r的子序列。
组合元组按照输入的iterable顺序按词典顺序发布。 因此,如果输入的iterable为解释,则绑定元组也会在排序的itertools.combinations(iterable, r)中生成。
即使元素的值相同,也会认为元素因位置而异。 如果元素各不相同,则每个组合没有重复元素。已排序
顺序
差频组合(iterable,r ) : #组合(ABCD ',2 )-- abacadbcbdcd #组合范围(range )4), 3---- 012013023123 pool=tuple (iterable ) n=len (pool ) ifrn : return indices=list (range (r ) yieldtuple ) pool=in-r : break else : return indices [ I ]=1forjinrange (i1,r ) :indices(j )=indices (j-1 )1yieldtuple )
defcombinations(iterable,r ) :pool=tuple ) n=len (pool ) forindicesinpermutations (range ) n ),r ) 3: if sortatior
连续返回iterable元素生成的长度为r的数组。
如果未指定r或为None,则缺省情况下将r设置为iterable的长度。 在这种情况下,将生成所有全长数组。
数组元组按照输入的iterable顺序按词典顺序发布。 因此,如果输入的iterable已排序,联接元组也会按排序顺序生成。
即使元素的值相同,也会认为元素因位置而异。 如果元素的值不同,则每个数组中的元素的值不重复。
相当于排列组合枚举所有情况
defpermutations(iterable,r=None ) :#permutations ) ' ABCD ', 2----abACadbaBCBDcaCBCDdadbDC# permutations---- 012021102120201210 pool=tuple (iterable ) n=len ) pool r=nifrisnoneeelserifrn : return indices=listes -1) yield tuple (pool [ I ] foriinindices [ : r ] ) whilen : foriinreversed (range (r ) ) : cycles [ I ]-=1if=indices [ I : I1] cycles [ I ]=n-I else 3360 j=cycles [ I ] indices indices [ I ] yield tuple (pool [ I ] forininindices [
可互换, r=None ) :pool=tuple ) iterable ) n=len ) pool ) r=nifrisnoneelserforindicesinproduct repeat=r (: if len (set )
可迭代对象输入的笛卡儿积。
源码:环。 例如,product(a,b )和) x,y ) for x in A for y in B )返回相同的结果。
嵌套循环类似于里程表,为注意,每次迭代都将最右边的元素向后重复。 这个模式形成词典顺序。 因此,如果输入的可迭代对象已排序,则会按顺序提交笛卡儿积元组。
要计算可重复对象本身的combinations,请将可选参数repeat设置为permutations。 例如,product(a,repeat=4)和product(a,a,a )是相同的。
此函数几乎相当于以下代码,但实际实现方案不会在内存中创建中间结果:
defproduct(*args,repeat=1) :#product ) ABCD ',' xy ' )--axaybxbyCXcydxdy#product ) range ) 2, repeat=3----0000100110010110111 pools=[ tuple (pool ) forpoolinargs ] * repeat result=[ ] forpolinpools 3360 fool
官方API文档