i tried to gradually interleave one list with another. i mean: starting from the lists
a0 = list(range(3)) # [0, 1, 2]
a1 = list(range(10, 13)) # [10, 11, 12]
i would like to be able to iterate over the combinations
[0, 1, 2]
[10, 1, 2]
[0, 11, 2]
[10, 11, 2]
[0, 1, 12]
[10, 1, 12]
[0, 11, 12]
[10, 11, 12]
where first no element of a0
is replaced by the corresponding element of a1
, then one, then two and then all of them.
what i came up with so far i this:
a01 = list(zip(a0, a1))
for i in range(1<<len(a0)):
print(list(item[(i >> j) & 1] for j, item in enumerate(a01)))
where i zip
the lists together and use i
as a flag that tells me from what list to select an element.
this seems quite inelegant. is there something more elegant? i feel that itertools
provides something that could be used here but i could not figure out anything so far.
the suggestion in the duplicate applied here is:
from itertools import product
for item in product(*zip(a0, a1)):
print(item)
this produces the desired results (in a different order).
to get the order correct meowgoesthedog suggests in the comments:
list(map(lambda x: tuple(reversed(x)), product(*reversed(list(zip(a0, a1))))))
this answers the question.