在列表元素内创建所有可能的组合

时间:2017-10-05 09:02:12

标签: python-3.x list itertools

我需要探索列表的每个排列。让我们说我有这个启动变量:

samplelist = [1, 2, 3, 4, 5, 6, 7, 8, 9]

示例输出为:

output = [[1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 3, 2, 4, 5, 6, 7, 8, 9], [1, 3, 4, 2, 5, 6, 7, 8, 9], [1, 3, 5, 3, 2, 6, 7, 8, 9]] .... and so on.

这就是我的所作所为:

import itertools
samplelist = [1, 2, 3, 4, 5, 6, 7, 8, 9]

def combinations(iterable, r):

    pool = tuple(iterable)
    n = len(pool)
    if r > n:
        return
    indices = range(r)
    yield tuple(pool[i] for i in indices)
    while True:
        for i in reversed(range(r)):
            if indices[i] != i + n - r:
                break
        else:
            return
        indices[i] += 1
        for j in range(i+1, r):
            indices[j] = indices[j-1] + 1
        yield tuple(pool[i] for i in indices)

list(combinations_with_replacement(samplelist, 9))

由于列表的长度为9,因此9的阶乘为362,880。我试图获取列表中元素的所有组合

但我的输出并不是我想要实现的目标。

1 个答案:

答案 0 :(得分:0)

itertools.permutations(samplelist)返回9!列表