Reputation: 99
I am looking for a simple way to solve this. Lets say I have a list of lists, of which there are an uncertain number of lists in those lists:
lists = [
[[1,2,3,4],[2,3,4,5]],
[[1,2,3,4],[2,3,4,5],[3,4,5,6]],
[[1,2,3,4]],
[[1,2,3,4],[2,3,4,5]]
]
What I can't figure out is now to generate a permutation of all possible combinations while keeping the first level of lists
in the same order. I have messed around with nested for
loops and the any()
function with little success. The nested for loops do not work, because in reality, len(lists)
is much larger, and would take len(lists)
amount of for
loops. Does anyone have any ideas?
In the above example, a few possible permutations would be:
[[1,2,3,4],
[1,2,3,4],
[1,2,3,4],
[1,2,3,4]]
[[1,2,3,4],
[1,2,3,4],
[1,2,3,4],
[2,3,4,5]]
[[2,3,4,5],
[1,2,3,4],
[1,2,3,4],
[2,3,4,5]]
[[2,3,4,5],
[3,4,5,6],
[1,2,3,4],
[2,3,4,5]]
Upvotes: 0
Views: 128
Reputation: 304375
As @DSM suggests, you may be looking for the cartesian product. Permutations means something different.
>>> import pprint, itertools as it
>>> lists = [
... [[1,2,3,4],[2,3,4,5]],
... [[1,2,3,4],[2,3,4,5],[3,4,5,6]],
... [[1,2,3,4]],
... [[1,2,3,4],[2,3,4,5]]
... ]
>>> pprint.pprint(list(it.product(*lists)))
[([1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]),
([1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4], [2, 3, 4, 5]),
([1, 2, 3, 4], [2, 3, 4, 5], [1, 2, 3, 4], [1, 2, 3, 4]),
([1, 2, 3, 4], [2, 3, 4, 5], [1, 2, 3, 4], [2, 3, 4, 5]),
([1, 2, 3, 4], [3, 4, 5, 6], [1, 2, 3, 4], [1, 2, 3, 4]),
([1, 2, 3, 4], [3, 4, 5, 6], [1, 2, 3, 4], [2, 3, 4, 5]),
([2, 3, 4, 5], [1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]),
([2, 3, 4, 5], [1, 2, 3, 4], [1, 2, 3, 4], [2, 3, 4, 5]),
([2, 3, 4, 5], [2, 3, 4, 5], [1, 2, 3, 4], [1, 2, 3, 4]),
([2, 3, 4, 5], [2, 3, 4, 5], [1, 2, 3, 4], [2, 3, 4, 5]),
([2, 3, 4, 5], [3, 4, 5, 6], [1, 2, 3, 4], [1, 2, 3, 4]),
([2, 3, 4, 5], [3, 4, 5, 6], [1, 2, 3, 4], [2, 3, 4, 5])]
Upvotes: 1