Python 将嵌套列表合并到子列表的唯一组合中

Python 将嵌套列表合并到子列表的唯一组合中,python,python-3.x,list,nested,combinations,Python,Python 3.x,List,Nested,Combinations,我有一个嵌套的表单列表: [[[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]]] 我知道有很多清单,但我需要那种形式的。我不知道从哪里开始。没关系,我解决了。下面是一个工作示例 tes

我有一个嵌套的表单列表:

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

我知道有很多清单,但我需要那种形式的。我不知道从哪里开始。

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

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

您可以使用
itertools。组合

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

您可以将字典与以下内容一起使用:

结果:

{('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
循环的数量。

我比你先做到这一点。请看另一个答案:)做得好,但请记住,遍历索引不是python式的方法。你是对的,你的答案比我的更优雅,因此我将选择它作为正确答案。
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']]]