Python反向生成器 [英] Python Reverse Generator
问题描述
我正在寻找一种反转生成器对象的方法.我知道如何反转序列:
I'm looking for a way to reverse a generator object. I know how to reverse sequences:
foo = imap(seq.__getitem__, xrange(len(seq)-1, -1, -1))
但是使用生成器作为输入并使用反向生成器作为输出(len(seq)保持不变,因此可以使用原始序列的值)是否有可能类似?
But is something similar possible with a generator as the input and a reversed generator as the output (len(seq) stays the same, so the value from the original sequence can be used)?
推荐答案
除非将生成器强制转换为序列并从中创建迭代器,否则无法以任何通用方式反转生成器.在计算出较早的项之前,不一定要知道生成器的后项.
You cannot reverse a generator in any generic way except by casting it to a sequence and creating an iterator from that. Later terms of a generator cannot necessarily be known until the earlier ones have been calculated.
更糟糕的是,直到您碰到生成器,您才知道它是否会遇到StopIteration异常,因此无法知道序列中的第一个术语.
Even worse, you can't know if your generator will ever hit a StopIteration exception until you hit it, so there's no way to know what there will even be a first term in your sequence.
最好的办法是编写一个reversed_iterator函数:
The best you could do would be to write a reversed_iterator function:
def reversed_iterator(iter):
return reversed(list(iter))
当然,您也可以使用基于imap的迭代版本替换其中的reversed,以保存一个列表创建.
You could also, of course, replace reversed in this with your imap based iterative version, to save one list creation.
这篇关于Python反向生成器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!