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

时间:2018-10-16 09:06:36

标签: 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]]]

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

3 个答案:

答案 0 :(得分: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']]]

答案 1 :(得分:0)

没关系,我解决了。这是一个有效的示例。

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

答案 2 :(得分:0)

您可以将字典与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循环的数量。

相关问题