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
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.
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))
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.
Edit: 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.