多个列表的可能组合

时间:2019-02-26 12:06:02

标签: python list

我在列表中有一组变量

list = [ 'A', 'B', 'C']

我迭代地从列表中删除一个变量,并将其附加到列表列表中的原始列表中,当列表中只有一个项目时停止。例如,使用上面的列表的输出将是:

list_of_var_lists = [
[['A', 'B', 'C'], ['A', 'B'], ['A']],
[['A', 'B', 'C'], ['A', 'B'], ['B']],
[['A', 'B', 'C'], ['A', 'C'], ['A']],
[['A', 'B', 'C'], ['A', 'C'], ['C']],
[['A', 'B', 'C'], ['B', 'C'], ['B']],
[['A', 'B', 'C'], ['B', 'C'], ['C']]
]

我要如何处理任何大小的列表?

非常感谢,J

1 个答案:

答案 0 :(得分:4)

这是使用itertools.permutations的解决方案。它是生成器,而不是庞大的列表列表,因为此类子列表的数量呈指数级增长:

import itertools

def list_unpacker(ls):
    for p in itertools.permutations(ls):
        sublists = []
        current_list = ls[:]
        sublists.append(current_list)
        for x in p[:-1]:
            current_list = [y for y in current_list if y != x]
            sublists.append(current_list)
        yield sublists

for lists in list_unpacker(['a','b','c']):
    print(lists)

输出:

[['a', 'b', 'c'], ['b', 'c'], ['c']]
[['a', 'b', 'c'], ['b', 'c'], ['b']]
[['a', 'b', 'c'], ['a', 'c'], ['c']]
[['a', 'b', 'c'], ['a', 'c'], ['a']]
[['a', 'b', 'c'], ['a', 'b'], ['b']]
[['a', 'b', 'c'], ['a', 'b'], ['a']]
相关问题