我過4列表迭代器編寫循環是這樣的:ValueError異常的StopIteration之前提出地圖(接下來,iterables)
it0 = iter(['foo','bar'])
it1 = iter(['bar','foo'])
it2 = iter(['foo','foo'])
it3 = iter(['bar','bar'])
try:
a, b, c, d = map(next, (it0, it1, it2, it3))
while True:
#some operations that can raise ValueError
if a+b+c+d == 'foobar'*2:
a, b, c, d = map(next, (it0, it1, it2, it3))
elif a+b == 'foobar':
c, d = map(next,(it2, it3))
else:
a, b = map(next,(it0, it1))
except StopIteration:
pass
但是當我運行在Python3這個代碼,我得到前提出了ValueError: not enough values to unpack (expected 2, got 0)
預計StopIteration
。
我不想在except
語句中捕獲ValueError
,因爲while循環中的某些操作也可能導致應該停止程序的ValueError
。
next
在分配前怎麼沒有提出異常?
在Python2.7中,首先提出StopIteration
。
你或許應該修正這個錯誤,但FYI你可以趕上一個以上的異常類型,不會夾住東西:'除了StopIteration異常,ValueError異常: do_something()' – jDo
酷酷..你的問題只是讓我相信你不知道這一點。它的寫法就好像你唯一的選擇就是捕獲* StopIteration或者ValueError。不是都。無論如何,我認爲彼得斯先生可能已經解決了下面的*實際問題。 – jDo
@jDo,我只想捕獲StopIteration來停止while循環,但我希望程序在出現ValueError時停止。如果兩者都被捕獲並且ValueError可能意味着StopIteration,則會引起混淆。正如你所說的問題解決了。 –