解决组合问题,并尝试输出列表列表作为输入的列表。我找到的最接近的解决方案是在这里:All combinations of a list of lists
但是,我不需要列表之间的所有组合,而希望在每个列表中。例如
[[1],[2,3],[4,5,6]] -> [[1],[2],[3],[2,3],[4],[5],[6],[4,5],[4,6],
[5,6],[4,5,6]]
答案 0 :(得分:2)
贷记How can I find all the subsets of a set, with exactly n elements?
首先找到一种方法来查找一个列表的所有子集(也称为幂集):
from itertools import chain, combinations
def powerset(iterable):
"""
powerset([1,2,3]) --> [[1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]
"""
xs = list(iterable)
return [list(x) for x in chain.from_iterable(combinations(xs,n) for n in range(len(xs)+1)) if x]
然后迭代每个列表:
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]]
答案 1 :(得分:1)
下面,我定义了一个辅助函数,以从序列中获取所有组合,然后将其应用于输入列表的每个子列表,并将结果chain
一起使用。
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)]
答案 2 :(得分:0)
与itertools.combinations
:
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]]