繁体   English   中英

如何从 itertools.permutations 中取出一个元素?

[英]How do I take out an element from itertools.permutations?

from itertools import permutations
perms = permutations("hello",5)

这给了我一个奇怪的 <> 我不明白的东西。 它似乎适用于 go

for i in perms:
    print(i)

但我不想遍历所有排列,因为它们有很多。 所以我希望能够做类似的事情

perms[index]

给出 ("h","e","l","l","o")。 但这会中断,因为它“不可下标”。 那么我如何从中得到 ("h","e","l","l","o") 呢? 谢谢!

如果您想按字典顺序获得序列的nth排列,而不必生成所有这些排列,您可以使用从此处改编的这段代码片段:

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']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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