反转大型迭代器的有效方法

问题描述

这听起来可能有点疯狂,但我有一个包含 N = 10**409 元素的迭代器。有没有办法从这个“列表”的末尾获取项目? IE。当我调用 next(iterator) 时,它给了我我想要成为的最后一件事,但要达到我想要成为的第一件事,我需要调用 next(iterator) N 次。 如果我执行类似 list(iterator).reverse() 的操作,它当然会因内存不足而崩溃。

编辑:迭代器如何与简化示例一起使用:

# prints all possible alphabetical character combinations that can fit in a tweet
chars = "abcdefghijklmnopqrstuvwxyz "
cproduct = itertools.product(chars,repeat=250)
for subset in cproduct:
    print(''.join(subset))

# will start with `aaaaaaaa...aaa`
# but I want it to start with `zzz...zzz`

解决方法

对于某些问题,您可以反向计算元素。对于您提供的示例,您可以简单地将您要购买的产品的商品反向。

在这个例子中,我们在取乘积之前反转符号以获得“反向迭代器”:

>>> symbols = "abc"

>>> perms = itertools.product(symbols,repeat=5)
>>> perms = ["".join(x) for x in perms]
>>> perms
['aaaaa','aaaab','aaaac','aaaba','aaabb',...,'cccbb','cccbc','cccca','ccccb','ccccc']

>>> perms_rev = itertools.product(symbols[::-1],repeat=5)
>>> perms_rev = ["".join(x) for x in perms_rev]
>>> perms_rev
['ccccc','aaaaa']

>>> perms_rev == perms[::-1]
True