from itertools import permutations
perms = permutations("hello",5)这给了我一个奇怪的<>东西,我不明白。这看起来很管用
for i in perms:
print(i)但我不想遍历所有的排列,因为有很多排列。所以我想做一些像这样的事情
perms[index]给("h","e","l","l","o")但这会破坏它,因为它是“不可订阅的”。那么如何才能得到("h","e","l","l","o")呢?谢谢!
发布于 2019-11-07 19:23:21
如果您希望获得按字典顺序排列的序列的nth排列,而不必生成所有序列,则可以使用改编自here的代码片段
from functools import reduce
def Factorial (n):
return reduce(lambda x, y: x * y, range(1, n + 1), 1)
def GetNthPermutation (seq, index):
seqc = list(seq[:])
result = []
fact = Factorial(len(seq))
index %= fact
while seqc:
fact = fact // len (seqc)
choice, index = index // fact, index % fact
result += [seqc.pop(choice)]
return result它可以像这样使用:
>>> print(GetNthPermutation(list("hello"), 3))
['h', 'e', 'l', 'o', 'l']https://stackoverflow.com/questions/58747302
复制相似问题