避免Python Generator中的Multiple Next()语句 [英] Avoid Multiple Next () Statement in Python Generator
问题描述
我正在使用一个返回生成器的库。有没有办法在不使用多个 next()语句的情况下从特定迭代开始?
I'm using a library that returns a generator. Is there a way to start at a particular iteration without using multiple next () statement?
在一个简单的for循环中,我可以执行以下。
In a simple for loop, I could do the following.
array = [2, 5, 1, 4, 3]
for i in array [2:]:
# do something
在发电机中,我不能如上所示。相反,我将不得不使用多个 next()语句从第3个索引开始。当尝试做与for循环相同的操作时,我得到一个错误,上面写着生成器不可编写脚本。
In a generator, I couldn't do as shown above. Instead I'll have to use multiple next () statements to start at the 3rd index. When attempting to do the same as the for loop, I get an error that said, "generator is not scriptable."
推荐答案
itertools.islice
这样做,但实际上,它只是为你一遍又一遍地调用 next
(虽然在CPython的C层,所以它比手动操作更快)。
itertools.islice
does this, but in reality, it's just invoking next
for you over and over (though at the C layer in CPython, so it's faster than doing it manually).
for i in itertools.islice(mygenerator, 2, None):
# do something
这篇关于避免Python Generator中的Multiple Next()语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!