【问题标题】:Combinations of lists within lists [duplicate]列表中列表的组合[重复]
【发布时间】:2019-04-30 02:29:19
【问题描述】:

解决一个组合问题并尝试输出一个包含列表列表作为输入的列表。我找到的最接近的解决方案在这里: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]]

【问题讨论】:

  • 这个列表有多深?它只会是列表的列表吗?另外,输出列表的顺序重要吗?

标签: python combinations


【解决方案1】:

感谢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]]

【讨论】:

  • 很好......正是我需要它做的事情。欣赏它
【解决方案2】:

下面,我定义了一个辅助函数来获取序列中的所有组合,然后将其应用于输入列表的每个子列表,并将结果一起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)]

【讨论】:

    【解决方案3】:

    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]]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-10
      • 2013-06-05
      • 2017-09-04
      • 1970-01-01
      相关资源
      最近更新 更多