【问题标题】:Combine nested list into unique combinations of sublists将嵌套列表组合成子列表的唯一组合
【发布时间】:2018-10-16 09:06:35
【问题描述】:

我有一个嵌套列表:

[[[a, [a1, a2, a3]],[b, [b1, b2, b3]], [c, [c1, c2, c3]]]

我怎样才能把它变成初始元素的独特组合,形式为:

[[[a, b],[a1, a2, a3, b1, b2, b3]],[[a,c],[a1, a2, a3, c1, c2, c3]], [[b,c],[b1, b2, b3, c1, c2, c3]]]

我知道有很多列表,但我需要这种形式。我不知道从哪里开始。

【问题讨论】:

    标签: python python-3.x list nested combinations


    【解决方案1】:

    你可以使用itertools.combinations:

    from itertools import combinations
    l = [['a', ['a1', 'a2', 'a3']],['b', ['b1', 'b2', 'b3']], ['c', ['c1', 'c2', 'c3']]]
    print([[[i for i, _ in c], [i for _, l in c for i in l]] for c in combinations(l, 2)])
    

    这个输出:

    [[['a', 'b'], ['a1', 'a2', 'a3', 'b1', 'b2', 'b3']], [['a', 'c'], ['a1', 'a2', 'a3', 'c1', 'c2', 'c3']], [['b', 'c'], ['b1', 'b2', 'b3', 'c1', 'c2', 'c3']]]

    【讨论】:

    • 我打败了你。查看其他答案:)
    • 干得好,但请记住,遍历索引不是 Python 的方式。
    • 你是对的,你的答案比我的优雅,所以我会选择它作为正确答案。
    【解决方案2】:

    没关系,我解决了。这是一个工作示例。

    test = [['a', ['a1', 'a2', 'a3']],['b', ['b1', 'b2', 'b3']], ['c', ['c1', 'c2', 'c3']]]
    
    nested_list = []
    for (idx1, idx2) in itertools.combinations(range(len(test)), r=2):
        (elem1, elem2), (elem3, elem4) = test[idx1], test[idx2]
        nested_list += [[elem1, elem3], elem2+elem4]
    
    nested_list
    
    [['a', 'b'],
     ['a1', 'a2', 'a3', 'b1', 'b2', 'b3'],
     ['a', 'c'],
     ['a1', 'a2', 'a3', 'c1', 'c2', 'c3'],
     ['b', 'c'],
     ['b1', 'b2', 'b3', 'c1', 'c2', 'c3']]
    

    【讨论】:

      【解决方案3】:

      您可以使用带有itertools.combinations 的字典:

      from itertools import combinations, chain
      
      L = [['a', ['a1', 'a2', 'a3']], ['b', ['b1', 'b2', 'b3']], ['c', ['c1', 'c2', 'c3']]]
      
      d = dict(L)
      
      res = {comb: list(chain.from_iterable(map(d.__getitem__, comb))) \
             for comb in combinations(d, 2)}
      

      结果:

      {('a', 'b'): ['a1', 'a2', 'a3', 'b1', 'b2', 'b3'],
       ('a', 'c'): ['a1', 'a2', 'a3', 'c1', 'c2', 'c3'],
       ('b', 'c'): ['b1', 'b2', 'b3', 'c1', 'c2', 'c3']}
      

      或者,如果您更喜欢嵌套列表:

      res_lst = [[list(comb), list(chain.from_iterable(map(d.__getitem__, comb)))] \
                 for comb in combinations(d, 2)]
      
      # [[['a', 'b'], ['a1', 'a2', 'a3', 'b1', 'b2', 'b3']],
      #  [['a', 'c'], ['a1', 'a2', 'a3', 'c1', 'c2', 'c3']],
      #  [['b', 'c'], ['b1', 'b2', 'b3', 'c1', 'c2', 'c3']]]
      

      在这两种情况下,想法都是减少 Python 级 for 循环的数量。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-06-01
        • 2017-05-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-07-31
        相关资源
        最近更新 更多