I would like to mix every element of two lists with eachother, they have the same length:
list1 = [(m0, m0 b), (m1, m1 b), (m2, m2 b),...]
list2 = [(n0, n0 b), (n1, n1 b), (n2, n2 b),...]
to create a list like this:
new_list = [((m0, m0 b), (n0, n0 b)), ((m0, m0 b), (n1, n1 b)), ((m0, m0 b), (n2, n2 b)),..., ((m1, m1 b), (n0, n0 b)), ((m1, m1 b), (n1, n1 b)), ((m1, m1 b), (n2, n2 b)), ..., ((m2, m2 b), (n0, n0 b)), ((m2, m2 b), (n1, n1 b)), ((m2, m2 b), (n2, n2 b)), ...]
Update:
Solution
from itertools import product
list(product(list1, list2))
[((m0, m0 b), (n0, n0 b)),
((m0, m0 b), (n1, n1 b)),
((m0, m0 b), (n2, n2 b)),
((m1, m1 b), (n0, n0 b)),
((m1, m1 b), (n1, n1 b)),
((m1, m1 b), (n2, n2 b)),
((m2, m2 b), (n0, n0 b)),
((m2, m2 b), (n1, n1 b)),
((m2, m2 b), (n2, n2 b))]
CodePudding user response:
Use:
from itertools import product
list(product(list1, list2))
[((m0, m0 b), (n0, n0 b)),
((m0, m0 b), (n1, n1 b)),
((m0, m0 b), (n2, n2 b)),
((m1, m1 b), (n0, n0 b)),
((m1, m1 b), (n1, n1 b)),
((m1, m1 b), (n2, n2 b)),
((m2, m2 b), (n0, n0 b)),
((m2, m2 b), (n1, n1 b)),
((m2, m2 b), (n2, n2 b))]
CodePudding user response:
Using a comprehension with zip
and itertools.chain
from itertools import chain
m = [ ... ]
n = [ ... ]
b = ...
new_list = list(chain(*(((m1, m2 b), (n1, n2 b)) for (m1, m2), (n1, n2) in zip(m, n))))