簡體   English   中英

如何在try塊中為條件執行相同的代碼而不重復except子句中的代碼

[英]How can I execute same code for a condition in try block without repeating code in except clause

我正在檢查列表的連續索引,如果連續元素不相等或者列表索引超出范圍,我想執行相同的代碼。 這就是我正在嘗試的

for n in range(len(myList))
    try:
         if myList[n]==myList[n+1]:
             #some code
         else:
             #if they are not equal then do something
             #same code should execute if exception raised: index error  --> how do i do this?

有沒有辦法優雅地做到這一點,而不必以某種方式在except塊中重復相同的代碼?

執行此操作的一種簡單方法是僅修改if語句以檢查候選元素是否不是最后一個,從而避免需要異常子句,並保持代碼簡短。

    for n, i in enumerate(myList):
       if n+1 != len(myList) and i == myList[n+1]:
           #some code
       else:
           #if they are not equal then do something
           #This block will also be exicuted when last element is reached
for n in range(1, len(myList))
    if myList[n]==myList[n-1]:
         #some code
    else:
         #foo_bar()
#foo_bar()

看看這個(湯姆羅恩建議):

def foobar():
    #the code you want to execute in both case
for n in range(len(myList)):
    try:
        if myList[n]==myList[n+1]:
            #some code
        else:
            foobar()
    except IndexError:
        foobar()

其他答案適用於您可以避免首先提出異常的特定情況。 無法避免異常的更一般情況可以處理lambda函數,如下所示:

def test(expression, exception_list, on_exception):
    try:
        return expression()
    except exception_list:
        return on_exception

if test(lambda: some_function(data), SomeException, None) is None:
    report_error('Something happened')

這里的關鍵點是使它成為一個lambda推遲對可能引發異常的表達式的評估,直到test()函數的try / except塊中可以捕獲它。 test()返回評估結果,或者,如果引發exception_list中的exception_list ,則on_exception值。

這來自被拒絕的PEP 463中的一個想法。 lambda to the Rescue提出了同樣的想法。

(我在回答這個問題時給出了相同的答案,但我在這里重復一遍,因為這不是一個重復的問題。)

暫無
暫無

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

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