1

I have a list of lists such as [[0,1,2,3],[0,1,2,3], ..., [0,1,2,3]] whose length is not know a priori.

My goal is to loop through all combinations of permutations of the [0,1,2,3] sublists, each combination is a list of lists just like the original but where the order of some sublists have changed, eg. the second combination could be [[0,1,3,2],[0,1,2,3], ..., [0,1,2,3]] and the third [[0,3,1,2],[0,1,2,3], ..., [0,1,2,3]]. I will use each of those for something else.

I imagine it like one constructs the binary table, first one would loop through the permutations of the first sublist, keeping the rest of the sublists unmodified; once they are done, they advance one permutation in the second sublist and go back to the first and loop through it again, and so on. A simpler example:

| [0,1] | [0,1] | [0,1] |
| [0,1] | [0,1] | [1,0] |
| [0,1] | [1,0] | [0,1] |
| [0,1] | [1,0] | [1,0] |
| [1,0] | [0,1] | [0,1] |
| [1,0] | [0,1] | [1,0] |
| [1,0] | [1,0] | [0,1] |
| [1,0] | [1,0] | [1,0] |

I'm having trouble with this because the way I'm thinking about it looks like I would need to have a variable number of nested loops. I don't know how to think about it in terms of recursion because once recursion I would need to loop as well, and once I return something that loop is lost. Any help is appreciated.

miguelsxvi
  • 27
  • 6
  • 1
    It would better to show example with lot smaller data like `[[1,2],[3,4], [5,6]]` – azro Jul 04 '21 at 15:13

1 Answers1

1

You can use itertools.product with itertools.permutations:

import itertools as it
d = [[0,1,2,3], [0,1,2,3], [0,1,2,3]]
r = list(it.product(*[it.permutations(i, len(i)) for i in d]))

Output:

[((0, 1, 2, 3), (0, 1, 2, 3), (0, 1, 2, 3)),  
 ((0, 1, 2, 3), (0, 1, 2, 3), (0, 1, 3, 2)), 
 ((0, 1, 2, 3), (0, 1, 2, 3), (0, 2, 1, 3)), 
 ((0, 1, 2, 3), (0, 1, 2, 3), (0, 2, 3, 1)), 
 ((0, 1, 2, 3), (0, 1, 2, 3), (0, 3, 1, 2)), 
 ((0, 1, 2, 3), (0, 1, 2, 3), (0, 3, 2, 1)), 
 ((0, 1, 2, 3), (0, 1, 2, 3), (1, 0, 2, 3)), 
 ((0, 1, 2, 3), (0, 1, 2, 3), (1, 0, 3, 2)), 
 ((0, 1, 2, 3), (0, 1, 2, 3), (1, 2, 0, 3)), 
 ((0, 1, 2, 3), (0, 1, 2, 3), (1, 2, 3, 0)),
 ...
]
Ajax1234
  • 69,937
  • 8
  • 61
  • 102
  • Thank you, just what I was looking for. I've never seen the asterisk used in that way, can you tell me what it does? – miguelsxvi Jul 04 '21 at 15:23
  • @miguelsxvi The `*` [unpacks](https://stackoverflow.com/questions/36901/what-does-double-star-asterisk-and-star-asterisk-do-for-parameters) an iterator in either a signature or container. – Ajax1234 Jul 04 '21 at 15:27