在Python中,except如何用于迭代器?
你能解释一下为什么在这个例子中从来没有执行过except子句,也从来没有调用过print吗在Python中,except如何用于迭代器?,python,iterator,yield,Python,Iterator,Yield,你能解释一下为什么在这个例子中从来没有执行过except子句,也从来没有调用过print吗 def h(lst): try: yield from lst except StopIteration: print('ST') t = h([1,2]) next(t) >>> 1 next(t) >>> 2 next(t) >>> Traceback (most recent call last): File "<
def h(lst):
try:
yield from lst
except StopIteration:
print('ST')
t = h([1,2])
next(t)
>>> 1
next(t)
>>> 2
next(t)
>>> Traceback (most recent call last):
File "<ipython-input-77-f843efe259be>", line 1, in <module>
next(t)
StopIteration
您的下一个调用在h函数之外,因此不在try/except子句的范围内。要进行比较,请尝试以下方法:
def h(lst):
yield from lst
t = h([1,2])
然后重复运行:
try:
print(next(t))
except StopIteration:
print('ST')
结果:
1
2
'ST'
'ST'
'ST'
...
您的下一个调用在h函数之外,因此不在try/except子句的范围内。要进行比较,请尝试以下方法:
def h(lst):
yield from lst
t = h([1,2])
然后重复运行:
try:
print(next(t))
except StopIteration:
print('ST')
结果:
1
2
'ST'
'ST'
'ST'
...
StopIteration由引发,而不是来自以下方面的收益:
nextiterator[,默认值]
通过调用迭代器的uuu next_uuu方法从迭代器中检索下一项。如果给定默认值,则在迭代器耗尽时返回,否则将引发StopIteration
这样你就可以结束下一次通话了
然后你就这样使用它:
>>> t = h([1,2])
>>> next_or_print(t)
1
>>> next_or_print(t)
2
>>> next_or_print(t)
ST
请注意,next还有第二个参数,允许提供默认值而不是StopIteration:
StopIteration由引发,而不是来自以下方面的收益:
nextiterator[,默认值]
通过调用迭代器的uuu next_uuu方法从迭代器中检索下一项。如果给定默认值,则在迭代器耗尽时返回,否则将引发StopIteration
这样你就可以结束下一次通话了
然后你就这样使用它:
>>> t = h([1,2])
>>> next_or_print(t)
1
>>> next_or_print(t)
2
>>> next_or_print(t)
ST
请注意,next还有第二个参数,允许提供默认值而不是StopIteration: