从python的zip保存迭代器

问题描述:

因此,我有一个必须多次调用的函数.该函数按如下方式成对遍历列表:

So, I have a function that I have to call a ton of times. That function iterates through a list by pairs like so:

for a, b in zip(the_list, the_list[1:]):
    # do stuff with a and b

我真的很想预先计算zip(the_list, the_list[1:])的结果,以便我可以重用它,而不必在每次调用此函数时都进行计算.

I'd really like to precompute the result of zip(the_list, the_list[1:]), so that I can reuse it and not have to calculate it each time I call this function.

不幸的是,由于zip(...)是一个生成器,所以我不能重用它的结果.有什么方法可以将生成器重置回开始,或者存储压缩的元组列表,以便我可以直接通过它进行迭代?

Unfortunately, since zip(...) is a generator, I can't reuse its result. Is there any way that I can reset the generator back to the beginning, or store the zipped tuple list so that I can iterate directly through that?

您可以像这样将生成器缓冲到列表中:

You can buffer a generator to a list like so:

z = list(zip(x, y))

但是,我怀疑这样做会带来很多性能上的好处,因为zip本身只是对其参数进行迭代,如果将其缓冲到列表中,则最终要做的就是这样做.当您呼叫zip时,实际上并没有太多的计算".

However, I doubt there'll be much performance benefit in this, since zip is itself just iterating over its arguments, which is what you'd end up doing if you buffered it to a list. There's not really much "computation" going on when you call zip.

这假设您使用的是Python 3,其中zip实际上确实返回了生成器.在Python 2中,zip返回一个列表,因此最好在函数调用之间重用此列表.

This assumes you're using Python 3, wherein zip really does return a generator. In Python 2, zip returns a list, so you're probably better off reusing this list between function calls.