【发布时间】:2015-05-08 03:06:07
【问题描述】:
我有以下实验代码,其功能类似于内置的zip。它试图做的事情应该简单明了,尝试一次返回一个压缩元组,直到我们停止生成器时出现IndexError。
def my_zip(*args):
i = 0
while True:
try:
yield (arg[i] for arg in args)
except IndexError:
raise StopIteration
i += 1
但是,当我尝试执行以下代码时,IndexError 没有被捕获,而是被生成器抛出:
gen = my_zip([1,2], ['a','b'])
print(list(next(gen)))
print(list(next(gen)))
print(list(next(gen)))
IndexError Traceback (most recent call last)
I:\Software\WinPython-32bit-3.4.2.4\python-3.4.2\my\temp2.py in <module>()
12 print(list(next(gen)))
13 print(list(next(gen)))
---> 14 print(list(next(gen)))
I:\Software\WinPython-32bit-3.4.2.4\python-3.4.2\my\temp2.py in <genexpr>(.0)
3 while True:
4 try:
----> 5 yield (arg[i] for arg in args)
6 except IndexError:
7 raise StopIteration
IndexError: list index out of range
为什么会这样?
编辑:
感谢@thefourtheye 为上面发生的事情提供了一个很好的解释。现在执行时又出现了一个问题:
list(my_zip([1,2], ['a','b']))
这条线永远不会回来,似乎挂了机器。现在发生了什么?
【问题讨论】:
-
粗略地说,如果我正确理解
yield的工作原理,您可以尝试执行def func(): try: return None except: pass之类的操作。 -
@Riliam,但您提供的代码会发现返回 1 / 0 之类的错误。
-
与您的问题无关,但您应该
return而不是提高 StopIteration - 在生成器 is deprecated and will change in the future 内显式提高 StopIteration。
标签: python python-3.x generator