将嵌套列表合并为子列表的唯一组合

2024-04-18 03:34:53 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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


Tags: a2元素表单列表a1b2a3形式
3条回答

可以将字典与^{}一起使用:

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循环的数量。你知道吗

您可以使用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']]]

没关系,我解决了。这是一个有效的例子。你知道吗

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

相关问题 更多 >