Python 如何在停止迭代之前停止对生成器调用next()
我有一个调用API并生成数据的函数。稍后,我使用next从生成器中检索数据,但是由于我不知道要提取多少数据,我最终执行next,直到它引发StopIteration异常Python 如何在停止迭代之前停止对生成器调用next(),python,python-3.x,generator,Python,Python 3.x,Generator,我有一个调用API并生成数据的函数。稍后,我使用next从生成器中检索数据,但是由于我不知道要提取多少数据,我最终执行next,直到它引发StopIteration异常 def get_data(): source = API_Instance() yield source.get_some_data() def parse_data(): data = get_data() while True: try: row_da
def get_data():
source = API_Instance()
yield source.get_some_data()
def parse_data():
data = get_data()
while True:
try:
row_data = next(data)
print(row_data)
except StopIteration:
break
这似乎是一种糟糕的方式。我有没有办法避免“尝试/例外”的障碍?想知道发电机已经耗尽了吗?找不到更好的词来形容它StopIteration异常是迭代器报告它是如何完成的。不过,有一种更简单的方法可以循环整个迭代器:
def parse_数据:
数据=获取数据
对于数据中的行_数据:
打印行数据
for循环将为您调用next并引发StopIteration。为什么不使用它呢?有趣的是,我在发布之前实际上测试了一些类似的东西,但是它打印了对生成器对象的引用。现在我意识到这是因为我在rangex中使用了for I:yield I来模拟get_数据。英雄联盟