简体   繁体   中英

How do I get all n! combinations of possible lists that can be created from numbers 1 to n?

It's kind of difficult to explain, so let me give an example:

For n=3 , I want to make all lists:

[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 1, 2]
[3, 2, 1]

How do I implement a function that each time returns the next list? (or one that returns a list of all possible lists?)

What you are looking for are the permutations of range(1, n + 1) :

from itertools import permutations

n = 3
for permutation in permutations(range(1, n + 1)):
  print(permutation)

range(1, n + 1) gives you the interval [1, n] , as range creates half open intervals. itertools.permutations takes all those values and gives you all possible combinations.

If you have the memory for it ( n! gets big pretty fast), you can collect them all into a list:

output = list(permutations(range(1, n + 1)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM