簡體   English   中英

except在Python中的迭代器如何工作?

[英]How except works for iterators in Python?

您能否向我解釋為什么在示例中從未執行過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 "<ipython-input-77-f843efe259be>", line 1, in <module>
next(t)

StopIteration

您的next調用不在 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'
...

StopIterationnext引發,而不是由以下命令yield from

next(iterator[, default])

通過調用其__next__()方法從迭代器中檢索下一項。 如果給定默認值 ,則在迭代器耗盡時返回它,否則引發StopIteration

因此,您可以包裝next呼叫。

def h(lst):
    yield from lst

def next_or_print(it):
    try:
        next(it)
    except StopIteration:
        print('ST')

然后像這樣使用它:

>>> t = h([1,2])
>>> next_or_print(t)
1
>>> next_or_print(t)
2
>>> next_or_print(t)
ST

注意next還具有第二個參數,該參數允許提供默認值而不是StopIteration

>>> t = h([1,2])
>>> next(t, 'ST')
1
>>> next(t, 'ST')
2
>>> next(t, 'ST')
ST
def h(lst):
  try:
    yield from lst
  except StopIteration:
    print('ST')
t = h([1, 2])
>>> print(t)
<generator object h at 0x7fbf6f08aa40>

函數“ h”返回一個生成器。 語句“ yield”作為“ return”不執行任何操作,僅返回生成器。 例外不會在代碼的那部分中。

必須將異常轉移到代碼的另一部分,在該部分中它將起作用。

def h(lst):
    yield from lst
t = h([1, 2])
next(t)
next(t)
try:
    next(t)
except StopIteration:
    print('ST')
ST

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM