def all_perms(elements):
if len(elements) <=1:
yield elements
else:
for perm in all_perms(elements[1:]):
for i in range(len(elements)):
# nb elements[0:1] works in both string and list contexts
yield perm[:i] + elements[0:1] + perm[i:]
在itertools.permutations的文档中列出了两种替代方法。这里有一个:
def permutations(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 210
pool = tuple(iterable)
n = len(pool)
r = n if r is None else r
if r > n:
return
indices = range(n)
cycles = range(n, n-r, -1)
yield tuple(pool[i] for i in indices[:r])
while n:
for i in reversed(range(r)):
cycles[i] -= 1
if cycles[i] == 0:
indices[i:] = indices[i+1:] + indices[i:i+1]
cycles[i] = n - i
else:
j = cycles[i]
indices[i], indices[-j] = indices[-j], indices[i]
yield tuple(pool[i] for i in indices[:r])
break
else:
return
另一个,基于itertools.product:
def permutations(iterable, r=None):
pool = tuple(iterable)
n = len(pool)
r = n if r is None else r
for indices in product(range(n), repeat=r):
if len(set(indices)) == r:
yield tuple(pool[i] for i in indices)
在Python 2.6以后:
(作为发电机返回。使用
list(permutations(l))
作为列表返回。)从Python2.6开始(如果在Python3上),您有一个用于此功能的标准库工具:^{} 。
如果您出于某种原因正在使用一个较旧的Python(<;2.6),或者只是想知道它是如何工作的,那么这里有一个很好的方法,来自http://code.activestate.com/recipes/252178/:
在
itertools.permutations
的文档中列出了两种替代方法。这里有一个:另一个,基于
itertools.product
:以下仅适用于Python2.6及更高版本的代码
首先,导入
itertools
:排列(顺序问题):
组合(顺序无关紧要):
笛卡尔积(带若干个iterable):
笛卡尔积(有一个iterable和它本身):
相关问题 更多 >
编程相关推荐