python - 如何生成列表的所有排列?

标签 python algorithm permutation combinatorics

如何生成列表的所有排列?例如:

permutations([])
[]

permutations([1])
[1]

permutations([1, 2])
[1, 2]
[2, 1]

permutations([1, 2, 3])
[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 1, 2]
[3, 2, 1]

最佳答案

使用 itertools.permutations来自标准库:

import itertools
list(itertools.permutations([1, 2, 3]))

改编自 here演示了如何实现 itertools.permutations:

def permutations(elements):
    if len(elements) <= 1:
        yield elements
        return
    for perm in permutations(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 - 如何生成列表的所有排列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/104420/

相关文章:

python - 仅当子类重写方法时才执行类属性的 copy()

python - 在 python 中格式化时间戳

python - 使用 block 大小将 CSV 文件从 s3 加载到 Pandas

c++ - 如何将新节点插入到单链表中,我们没有指针指向它的头部?

python - 在python中分配数组(列表)算法排列

python - 列表列表内和列表之间的排列 [python]

python - 有效地将列从数据框转换为字典列表

algorithm - 就地列表排序

python - 固定长度整数分区的唯一排列,其中每个元素都有一个最大值

python - 计算所有排列,包括所有子列表