簡體   English   中英

我如何獲得所有n? 可以從數字 1 到 n 創建的可能列表的組合?

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

這有點難以解釋,所以讓我舉個例子:

對於n=3 ,我想制作所有列表:

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

如何實現每次返回下一個列表的 function? (或者返回所有可能列表的列表?)

您正在尋找的是range(1, n + 1)的排列:

from itertools import permutations

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

range(1, n + 1)為您提供區間[1, n] ,因為range創建半開區間。 itertools.permutations采用所有這些值並為您提供所有可能的組合。

如果你有它的 memory( n!很快變大),你可以將它們全部收集到一個列表中:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM