python - How to get all mappings between two lists? -
we have 2 lists, , b:
a = ['a','b','c'] b = [1, 2]
is there pythonic way build set of maps between , b containing 2^n (here 2^3=8)? is:
[(a,1), (b,1), (c,1)] [(a,1), (b,1), (c,2)] [(a,1), (b,2), (c,1)] [(a,1), (b,2), (c,2)] [(a,2), (b,1), (c,1)] [(a,2), (b,1), (c,2)] [(a,2), (b,2), (c,1)] [(a,2), (b,2), (c,2)]
using itertools.product
, it's possible tuples:
import itertools p = it.product(a, b) [p p in p]
which gives:
out[3]: [('a', 1), ('a', 2), ('b', 1), ('b', 2), ('c', 1), ('c', 2)]
you can itertools.product
, zip
from itertools import product print [zip(a, item) item in product(b, repeat=len(a))]
output
[[('a', 1), ('b', 1), ('c', 1)], [('a', 1), ('b', 1), ('c', 2)], [('a', 1), ('b', 2), ('c', 1)], [('a', 1), ('b', 2), ('c', 2)], [('a', 2), ('b', 1), ('c', 1)], [('a', 2), ('b', 1), ('c', 2)], [('a', 2), ('b', 2), ('c', 1)], [('a', 2), ('b', 2), ('c', 2)]]
product(b, repeat=len(a))
produces
[(1, 1, 1), (1, 1, 2), (1, 2, 1), (1, 2, 2), (2, 1, 1), (2, 1, 2), (2, 2, 1), (2, 2, 2)]
then pick each element product , zip a
, desired output.
Comments
Post a Comment