python Python反向生成器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1561214/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 22:35:13  来源:igfitidea点击:

Python Reverse Generator

pythongeneratorreverse

提问by ak.

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))

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)?

但是,将生成器作为输入,将反向生成器作为输出(len(seq) 保持不变,因此可以使用原始序列中的值)是否有类似的可能?

回答by jcdyer

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.

您不能以任何通用方式反转生成器,除非将其转换为序列并从中创建迭代器。在计算了较早的项之前,不一定知道生成器的后续项。

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.

更糟糕的是,您无法知道生成器是否会在遇到 StopIteration 异常之前遇到它,因此无法知道序列中的第一项。

The best you could do would be to write a reversed_iterator function:

你能做的最好的事情是编写一个 reversed_iterator 函数:

def reversed_iterator(iter):
    return reversed(list(iter))

EDIT: You could also, of course, replace reversed in this with your imap based iterative version, to save one list creation.

编辑:当然,您也可以用基于 imap 的迭代版本替换这里的 reversed,以保存一个列表创建。

回答by Steve Losh

reversed(list(input_generator))is probably the easiest way.

reversed(list(input_generator))可能是最简单的方法。

There's no way to get a generator's values in "reverse" order without gathering all of them into a sequence first, because generating the second item could very well rely on the first having been generated.

如果不首先将所有生成器的值收集到一个序列中,就无法以“反向”顺序获取生成器的值,因为生成第二个项目很可能依赖于已生成的第一个项目。

回答by Kathy Van Stone

You have to walk through the generator anyway to get the first item so you might as well make a list. Try

无论如何,您必须遍历生成器才能获得第一个项目,因此您不妨列个清单。尝试

reversed(list(g))

where gis a generator.

哪里g是发电机。

reversed(tuple(g))

would work as well (I didn't check to see if there is a significant difference in performance).

也会起作用(我没有检查性能是否有显着差异)。