idealistikz
idealistikz

Reputation: 1267

What's the best way to obtain all the combinations (Cartesian product) of lists?

Suppose I have the following.

a = [[1,2,3],[4,5,6],[7,8,9]]
b = [['a','b'],['c','d'],['e','f']]

How do I obtain the following?

[1,2,3,'a','b']
[1,2,3,'c','d']
[1,2,3,'e','f']
[4,5,6,'a','b']
[4,5,6,'c','d']
[4,5,6,'e','f']
[7,8,9,'a','b']
[7,8,9,'c','d']
[7,8,9,'e','f']

Upvotes: 3

Views: 195

Answers (6)

Blender
Blender

Reputation: 298106

Just to see if you could condense the product expression, I came up with this:

>>> from itertools import product
>>> map(lambda x: sum(x, []), product(a, b))
[[1, 2, 3, 'a', 'b'], [1, 2, 3, 'c', 'd'], [1, 2, 3, 'e', 'f'], [4, 5, 6, 'a', 'b'], [4, 5, 6, 'c', 'd'], [4, 5, 6, 'e', 'f'], [7, 8, 9, 'a', 'b'], [7, 8, 9, 'c', 'd'], [7, 8, 9, 'e', 'f']]

Upvotes: 1

Anton Bessonov
Anton Bessonov

Reputation: 9803

just for fun, because answer from Maria is much better:

from itertools import product
a = [[1,2,3],[4,5,6],[7,8,9]]
b = [['a','b'],['c','d'],['e','f']]
print [sum(x, []) for x in product(a, b)]

Upvotes: 1

Lev Levitsky
Lev Levitsky

Reputation: 65781

In [1]: from itertools import product

In [2]: a = [[1,2,3],[4,5,6],[7,8,9]]

In [3]: b = [['a','b'],['c','d'],['e','f']]

In [4]: map(lambda x: x[0]+x[1], product(a, b))
Out[4]: 
[[1, 2, 3, 'a', 'b'],
 [1, 2, 3, 'c', 'd'],
 [1, 2, 3, 'e', 'f'],
 [4, 5, 6, 'a', 'b'],
 [4, 5, 6, 'c', 'd'],
 [4, 5, 6, 'e', 'f'],
 [7, 8, 9, 'a', 'b'],
 [7, 8, 9, 'c', 'd'],
 [7, 8, 9, 'e', 'f']]

Upvotes: 4

8bitwide
8bitwide

Reputation: 2071

a = [[1,2,3],[4,5,6],[7,8,9]]
b = [['a','b'],['c','d'],['e','f']]
c = []
for x in a:
    for y in b:
        print x + y
        c.append(x + y)

Upvotes: 1

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250881

>>> a = [[1,2,3],[4,5,6],[7,8,9]]
>>> b = [['a','b'],['c','d'],['e','f']]
>>> [x+y for x in a for y in b]
[[1, 2, 3, 'a', 'b'], [1, 2, 3, 'c', 'd'], [1, 2, 3, 'e', 'f'], [4, 5, 6, 'a', 'b'], [4, 5, 6, 'c', 'd'], [4, 5, 6, 'e', 'f'], [7, 8, 9, 'a', 'b'], [7, 8, 9, 'c', 'd'], [7, 8, 9, 'e', 'f']]

Upvotes: 2

Maria Zverina
Maria Zverina

Reputation: 11163

from itertools import product
a = [[1,2,3],[4,5,6],[7,8,9]]
b = [['a','b'],['c','d'],['e','f']]

print [x+y for (x,y) in product(a,b)]

Upvotes: 11

Related Questions