python - 多个列表的可能组合

标签 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

最佳答案

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

关于python - 多个列表的可能组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54885205/

相关文章:

python - 在模板中渲染和自定义 django 表单

list - LISP:力评估

c - 代码块中的动态分配

python - 提取文件名并将其用作 Pandas 中 DataFrame 的标签

python - 从 Python 列表中选择类(插件)

python - 用不同的色调分组覆盖对 seaborn 的 FacetGrid 的多次调用

python - 让所有属性出现在 python 的 `__dict__` 方法上

python - 如何设置xlim

python - 反转 DataFrame 中的单个列

Python漂亮的列表字典,缩写长列表