ibra
ibra

Reputation: 1304

How to combine elements of 3 lists or more two by two in python?

Given 3 or more lists, how to combine their elements two by two in an elegant pythonic way.

what i have tried (which works) so far:

list_a =[1,2,3]
list_b=["a","b","c"]
list_c = [0.1,0.2]
list_lists = [list_a, list_b, list_c]

results = []
for i in range(len(list_lists)-1):
    for j in range(i+1, len(list_lists)):
        results = results + [(x,y) for x in list_lists[i] for y in list_lists[j]] 
print(results)

Which produces:

[(1, 'a'), (1, 'b'), (1, 'c'), (2, 'a'), (2, 'b'), (2, 'c'), (3, 'a'), (3, 'b'), (3, 'c'), (1, 0.1), (1, 0.2), (2, 0.1), (2, 0.2), (3, 0.1), (3, 0.2), ('a', 0.1), ('a', 0.2), ('b', 0.1), ('b', 0.2), ('c', 0.1), ('c', 0.2)]

If we can do it like : list(itertools.combinations(*list_lists,2)), it will be great.

Thanks.

Upvotes: 0

Views: 448

Answers (2)

Alain T.
Alain T.

Reputation: 42139

First combine the lists two by two and for each list pair, get the product of their elements. You can do this in a list comprehension:

list_a = [1,2,3]
list_b = ["a","b","c"]
list_c = [0.1,0.2]
list_lists = [list_a, list_b, list_c]

from itertools import combinations,product
result = [ pair for listPair in combinations(list_lists,2)
                for pair in product(*listPair)]

print(result)
[(1, 'a'), (1, 'b'), (1, 'c'), (2, 'a'), (2, 'b'), (2, 'c'), (3, 'a'), 
 (3, 'b'), (3, 'c'), (1, 0.1), (1, 0.2), (2, 0.1), (2, 0.2), (3, 0.1), 
 (3, 0.2), ('a', 0.1), ('a', 0.2), ('b', 0.1), ('b', 0.2), ('c', 0.1), 
 ('c', 0.2)]

Upvotes: 1

StardustGogeta
StardustGogeta

Reputation: 3406

Looking for something like this?

import itertools

list_a =[1,2,3]
list_b=["a","b","c"]
list_c = [0.1,0.2]
list_lists = [list_a, list_b, list_c]

results = []
for pair in itertools.combinations(list_lists, 2):
    results.extend(itertools.product(*pair))
print(results)

We get every pair of lists and add the Cartesian product of the two lists to results.

Upvotes: 3

Related Questions