Given the list of sets s, I want to create the flattened_s as follows:
s = [{'a', 'b'}, {'c', 'd', 'e'}]
flattened_s = [['a', 'c'], ['a', 'd'], ['a', 'e'], ['b', 'c'], ['b', 'd'], ['b', 'e']]
This code can do the job:
flattened_s = []
for m in s[0]:
for n in s[1]:
flattened_s.append([m, n])
print(flattened_s)
However, if the list s is generalized to containing more than 2 sets in it, then how to do it? For example:
s = [{'a', 'b'}, {'c', 'd', 'e'}, {'f'}]
>Solution :
You could use itertools.product combined with the * operator:
from itertools import product
inp1 = [{'a', 'b'}, {'c', 'd', 'e'}]
inp2 = [{'a', 'b'}, {'c', 'd', 'e'}, {'f'}]
res1 = list(map(list, product(*inp1)))
# [['a', 'c'], ['a', 'e'], ['a', 'd'], ['b', 'c'], ['b', 'e'], ['b', 'd']]
res2 = list(map(list, product(*inp2)))
# [['a', 'c', 'f'],
# ['a', 'e', 'f'],
# ['a', 'd', 'f'],
# ['b', 'c', 'f'],
# ['b', 'e', 'f'],
# ['b', 'd', 'f']]