Qubix
Qubix

Reputation: 4353

Combine nested list into unique combinations of sublists

I have a nested list of the form:

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

How can I get this into unique combinations of the initial elements, of the form:

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

I know that's a lot of lists, but I need it in that form. I don't have an idea where to begin.

Upvotes: 2

Views: 110

Answers (3)

jpp
jpp

Reputation: 164793

You can use a dictionary with 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)}

Result:

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

Or, if you prefer nested lists:

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

The idea, in both cases, is to reduce the number of Python-level for loops.

Upvotes: 0

blhsing
blhsing

Reputation: 107040

You can use 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)])

This outputs:

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

Upvotes: 1

Qubix
Qubix

Reputation: 4353

Nevermind, I solved it. Here is a working example.

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

Upvotes: 0

Related Questions