How to pass through all row combinations in Python?
Question:
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?
Answers:
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),
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?
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),