获取特定的置换而不计算完整迭代器(itertools.置换)

2024-04-26 23:39:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我想访问一些固定的样本来排列一个长列表。显然我可以:

In [18]: import itertools

In [19]: l = [p for p in itertools.permutations(range(10))]

In [20]: len(l)
Out[20]: 3628800

In [21]: l[256766]
Out[21]: (0, 7, 3, 9, 5, 6, 4, 2, 1, 8)

但这会导致长列表l为列表创建而求值。10个项目清单仍然可行。为更大的列表挂起。在

有没有一种方法可以在不创建完整列表的情况下通过调用其编号来获得特定的排列?在

请注意,我不想访问随机洗牌。我希望它是相同的排列,最好是“置换号”匹配使用时调用的列表位置itertools.排列. 在

编辑:回复:复制。也欢迎回答与itertools模块相关的问题(见下面的讨论)。{rtools在上下文中可能仍然值得讨论。在


Tags: 项目方法inimport列表forlen情况
2条回答

您可以使用itertools.islice()

def get(perms, index):
    return next(itertools.islice(perms, index, index+1))

注意,这将部分耗尽迭代器。这意味着您不能在同一个迭代器上多次执行该操作。在


您也可以创建自己的类,这样它就可以记住已经生成了哪些值。这样,可以在同一对象上找到多个索引:

^{pr2}$

这并不难:

def nthperm(l, n):
    l = list(l)

    indices = []
    for i in xrange(1, 1+len(l)):
        indices.append(n % i)
        n //= i
    indices.reverse()

    perm = []
    for index in indices:
        # Using pop is kind of inefficient. We could probably avoid it.
        perm.append(l.pop(index))
    return tuple(perm)

这里的想法是,列表l的第n排列从第n // factorial(len(l) - 1)项开始,并继续l的其余元素的第{}排列。在

如果你测试它,你会发现它确实有效:

^{pr2}$

对于迭代itertools.permutations永远无法完成的输入,它的工作速度足够快:

>>> nthperm(range(100), factorial(100) // 2)
(50, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 2
1, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 4
1, 42, 43, 44, 45, 46, 47, 48, 49, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 6
2, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 8
2, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99)

相关问题 更多 >