首页 > 解决方案 > 多个列表的可能组合

问题描述

我在列表中有一组变量

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

标签: pythonlist

解决方案


这是使用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']]

推荐阅读