【问题标题】:How do I take out an element from itertools.permutations?如何从 itertools.permutations 中取出一个元素?
【发布时间】:2020-03-03 22:47:28
【问题描述】:
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") 呢? 谢谢!

【问题讨论】:

  • 尝试通过list(perms)转换成list
  • 我想这只是一个例子,但万一 OP 真的只想把"hello" 变成('h', 'e', 'l', 'l', 'o'),他们只需要tuple('hello')...
  • @CorentinPane 是的,我想我误解了。但即使是现在,我也不完全确定 OP 想要什么。例如,我无法理解他如何知道哪个索引包含("h","e","l","l","o")

标签: python python-3.x permutation itertools


【解决方案1】:

如果你想得到一个序列的字典序的nth排列而不需要全部生成,你可以使用这个改编自here的sn-p:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-04
    • 2012-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多