0

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'}]
marlon
  • 6,029
  • 8
  • 42
  • 76
  • "I want to" - Do you really? Or do you just want to solve your previous question, which you shouldn't do this way? – Kelly Bundy Dec 23 '21 at 09:56
  • Yes, I want to solve the previous question with the actual problem. There seems not to be a better solution for the previous problem. After I flatten this, I can use the previous solution to achieve goal. – marlon Dec 23 '21 at 10:06
  • There's a rather obvious better solution, and I'm confident mozway will be able to show it. – Kelly Bundy Dec 23 '21 at 10:25

1 Answers1

0

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']]
hilberts_drinking_problem
  • 11,322
  • 3
  • 22
  • 51