0

Say I have a 2D list:

[[1, 1, 1],
 [A, B, C],
 [D, E, F]]

I want the following combinations:

[1, 1, 1]
[1, 1, C]
[1, 1, F]
[1, B, 1]
[1, B, C]
[1, B, F]
[1, E, 1]
...

This continues on. I want it to be able to be done for any nxn 2D list.

Does any one know how to do this?

GeneralCode
  • 794
  • 1
  • 11
  • 26
  • Does this answer your question? [All combinations of a list of lists](https://stackoverflow.com/questions/798854/all-combinations-of-a-list-of-lists) – AMC Mar 06 '20 at 02:58

1 Answers1

3

In general, you can get the cartesian product with itertools.product. You'll need to transpose your input though (which I've done here with zip(*l):

In [8]: import itertools

In [9]: l = [[1, 1, 1],
   ...:  ['A', 'B', 'C'],
   ...:  ['D', 'E', 'F']]

In [10]: list(itertools.product(*zip(*l)))
Out[10]:
[(1, 1, 1),
 (1, 1, 'C'),
 (1, 1, 'F'),
 (1, 'B', 1),
 (1, 'B', 'C'),
 (1, 'B', 'F'),
 (1, 'E', 1),
 (1, 'E', 'C'),
 (1, 'E', 'F'),
 ('A', 1, 1),
Randy
  • 14,349
  • 2
  • 36
  • 42
  • 2
    Exactly the answer I was going to post, but it could use explanation (ideally piecemeal; `zip(*l)` is complicated enough, before you get into unpacking it again and passing it to `product`). Code-only answers aren't nearly as helpful, especially when it's pretty magical and the OP may be new to Python. – ShadowRanger Mar 06 '20 at 01:56
  • I am partly humbled by this. I haven't seen Python that made me wonder what in the world was going on in a while. Thanks for the Pythonic response. If someone can come up with a better Title for this question, please edit. – GeneralCode Mar 06 '20 at 02:02