-2

I have

l = [["a", "b", "c"], ["1", "2", "3"], ["x", "y", "z"]]

how can I get a list of the combination of all the elements?

combine(l)

should return

["a1x", "a2x", "a3x", "b1x", "b2x", "b3x", "c1x", "c2x", "c3x", 
 "a1y", "a2y", "a3y", "b1y", "b2y", "b3y", "c1y", "c2y", "c3y",
 "a1z", "a2z", "a3z", "b1z", "b2z", "b3z", "c1z", "c2z", "c3z"]
masber
  • 2,875
  • 7
  • 29
  • 49
  • That's invalid syntax. What is `a1b1c1`, for example, supposed to be, assuming the names `a1`, `b1` and `c1` are bound? – timgeb Mar 31 '16 at 09:22
  • @timgeb they are strings – masber Mar 31 '16 at 11:00
  • Why is `'c1a2b2'` or `'b1c1a2'` not in the result? – styvane Mar 31 '16 at 12:02
  • 2
    Possible duplicate of [Get the cartesian product of a series of lists in Python](http://stackoverflow.com/questions/533905/get-the-cartesian-product-of-a-series-of-lists-in-python) – glibdud Mar 31 '16 at 12:35

1 Answers1

1

This kind of combination you want is available in Python as the itertools.product function. You just have to post-process its output to join each tuple back as a string:

 import itertools
 l = [["a", "b", "c"], ["1", "2", "3"], ["x", "y", "z"]]
 combined = ["".join(combination) for combination in itertools.product(*l)]
 print(combined)

Results in:

['a1x', 'a1y', 'a1z', 'a2x', 'a2y', 'a2z', 'a3x', 'a3y', 'a3z', 'b1x', 'b1y', 'b1z', 'b2x', 'b2y', 'b2z', 'b3x', 'b3y', 'b3z', 'c1x', 'c1y', 'c1z', 'c2x', 'c2y', 'c2z', 'c3x', 'c3y', 'c3z']
jsbueno
  • 99,910
  • 10
  • 151
  • 209