Python 列表中的列表组合

Python 列表中的列表组合,python,combinations,Python,Combinations,处理组合问题并尝试输出一个列表,其中列表列表作为输入。我找到的最接近的解决方案是: 但是,我不希望列表之间的所有组合,而是在每个列表中。比如说 [[1],[2,3],[4,5,6]] -> [[1],[2],[3],[2,3],[4],[5],[6],[4,5],[4,6], [5,6],[4,5,6]] 下面,我定义了一个helper函数来获取序列中的所有组合,然后将其应用于输入列表的每个子列表和结果 from itertools import chain, c

处理组合问题并尝试输出一个列表,其中列表列表作为输入。我找到的最接近的解决方案是:

但是,我不希望列表之间的所有组合,而是在每个列表中。比如说

[[1],[2,3],[4,5,6]] -> [[1],[2],[3],[2,3],[4],[5],[6],[4,5],[4,6],            
[5,6],[4,5,6]]

下面,我定义了一个helper函数来获取序列中的所有组合,然后将其应用于输入列表的每个子列表和结果

from itertools import chain, combinations

l=[[1],[2,3],[4,5,6]]

def all_comb(seq):
    return chain.from_iterable(combinations(seq, i) for i in range(1, len(seq)+1))

print(list(chain.from_iterable(map(all_comb, l))))
# [(1,), (2,), (3,), (2, 3), (4,), (5,), (6,), (4, 5), (4, 6), (5, 6), (4, 5, 6)]
归功于

首先找到一种方法来查找一个列表(也称为幂集)的所有子集:

然后对每个列表进行迭代:

list_of_list = [[1],[2,3],[4,5,6]]
result = []
for x in list_of_list:
    result += powerset(x)
print(result)
输出:

[[1], [2], [3], [2, 3], [4], [5], [6], [4, 5], [4, 6], [5, 6], [4, 5, 6]]

使用
itertools.compositions

from itertools import combinations

l = [[1],[2,3],[4,5,6]]

combos = sum([[list(c) for c in combinations(x, i)] for x in l for i in range(1, len(x)+1)], [])

combos
>>> [[1], [2], [3], [2, 3], [4], [5], [6], [4, 5], [4, 6], [5, 6], [4, 5, 6]]

这个列表有多深?它只会是一个列表吗?还有,输出列表的顺序重要吗?很好…正是我需要它做的。感激
from itertools import combinations

l = [[1],[2,3],[4,5,6]]

combos = sum([[list(c) for c in combinations(x, i)] for x in l for i in range(1, len(x)+1)], [])

combos
>>> [[1], [2], [3], [2, 3], [4], [5], [6], [4, 5], [4, 6], [5, 6], [4, 5, 6]]