Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combinations of 2 lists [duplicate]

Input: [1, 2, 3] [a, b]

Expected Output: [(1,a),(1,b),(2,a),(2,b),(3,a),(3,b)]

This works, but is there a better way without an if statement?

[(x,y) for (x,y) in list(combinations(chain(a,b), 2)) if x in a and y in b]
like image 717
Kyle K Avatar asked Oct 24 '17 19:10

Kyle K


1 Answers

Use itertools.product, your handy library tool for a cartesian product:

from itertools import product

l1, l2 = [1, 2, 3], ['a', 'b']
output = list(product(l1, l2))
# [(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b'), (3, 'a'), (3, 'b')]
like image 92
user2390182 Avatar answered Nov 14 '22 17:11

user2390182