Thomas Cannon
Thomas Cannon

Reputation: 99

How can I generate a permutation of a list of lists while maintaining order on the highest level in Python?

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

Answers (1)

John La Rooy
John La Rooy

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

Related Questions