使用 Python 库生成排列
要在 Python 中生成列表的所有排列,一种方便的方法是利用 itertools.permutations 函数标准库。例如:
import itertools list(itertools.permutations([1, 2, 3]))
排列的自定义实现
或者,您可以创建自定义实现来计算排列:
def permutations(elements): if len(elements) <= 1: yield elements return for perm in permutations(elements[1:]): for i in range(len(elements)): yield perm[:i] + elements[0:1] + perm[i:]
其他方法
如果您如果您愿意,您还可以探索以下方法:
# Using reversed indices def permutations(iterable, r=None): 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 # Using 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 中生成排列?的详细内容。更多信息请关注PHP中文网其他相关文章!