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]
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')]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With