If I have the list my_list = [['a', 'b'], ['c', 'd', 'e']
, how can I create a list of all possible tuples where each tuple contains a single element from each sublist? For example:
('a', 'e')
is valid
('a', 'b')
is invalid
('b', 'c')
is valid
('c', 'd')
is invalid
Importantly, my_list
can contain any number of elements (sublists) and each sublist can be of any length. I tried to get a recursive generator off the ground, but it's not quite there.
Iād like to try and use recursion rather than itertools.
The logic was to iterate through 2 sublists at a time, and store those results as input to the next sublist's expansion.
def foil(lis=l):
if len(lis) == 2:
for x in l[0]:
for y in l[1]:
yield x + y
else:
for p in foil(l[:-1]):
yield p
for i in foil():
print(i)
However, this obviously only works for the len(my_list) == 2
. It also needs to work with, say, my_list = [['a'], ['b'], ['c', 'd']]
which would return:
('a', 'b', 'c')
('a', 'b', 'd')
Cheers!