简体   繁体   English

如何在try块中为条件执行相同的代码而不重复except子句中的代码

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

I am checking consecutive indices of a list and I want to execute same piece of code in case if the consecutive elements are not equal or if the list index is out of range. 我正在检查列表的连续索引,如果连续元素不相等或者列表索引超出范围,我想执行相同的代码。 Here's what I'm trying 这就是我正在尝试的

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?

Is there a way to do this elegantly without having to repeat the same code in the except block somehow? 有没有办法优雅地做到这一点,而不必以某种方式在except块中重复相同的代码?

A simple way of doing this is to just modify the if statement to check that the candidate element isn't the last one, avoiding the need for a exception clause, and keeping the code short. 执行此操作的一种简单方法是仅修改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()

Check out this(As Tom Ron suggested): 看看这个(汤姆罗恩建议):

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()

The other answers are good for the specific case where you can avoid raising the exception in the first place. 其他答案适用于您可以避免首先提出异常的特定情况。 The more general case where the exception cannot be avoided can be handled a lambda function as follows: 无法避免异常的更一般情况可以处理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')

The key point here is that making it a lambda defers evaluation of the expression that might raise an exception until inside the try/except block of the test() function where it can be caught. 这里的关键点是使它成为一个lambda推迟对可能引发异常的表达式的评估,直到test()函数的try / except块中可以捕获它。 test() returns either the result of the evaluation, or, if an exception in exception_list is raised, the on_exception value. test()返回评估结果,或者,如果引发exception_list中的exception_list ,则on_exception值。

This comes from an idea in the rejected PEP 463 . 这来自被拒绝的PEP 463中的一个想法。 lambda to the Rescue presents the same idea. lambda to the Rescue提出了同样的想法。

(I offered the same answer in response to this question , but I'm repeating it here because this isn't exactly a duplicate question.) (我在回答这个问题时给出了相同的答案,但我在这里重复一遍,因为这不是一个重复的问题。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 尝试......除了......除了......:如何避免重复代码 - try… except… except… : how to avoid repeating code 在python中,有没有办法在满足条件时进入try/except块,否则直接执行try块中的代码? - In python, is there a way to enter a try/except block if a condition is met, otherwise execute the code in the try block plainly? 如何在具有相同条件的一个 try/except 块中对单个和循环操作进行分组? - How can I group single and loop operations in one try/except block with same condition? 如何组织我的代码,以便重复尝试除了子句只存在一次? - How can I organize my code so that repeating try except clauses only exist once? Spyder ide:在 try except 子句中包围选定的代码块 - Spyder ide : surround a selected code block in try except clause 如何将try和except合并到python中的代码块中 - how to incorporate try and except into a block of code in python 如何使用 try/except 块优化代码? - How to optimize the code with try/except block? 我如何在尝试中使用循环代码,除了代码? - How can I use loop code on try, except code? 如何在“with”块中有条件地执行代码? - How can I conditionally execute code in a "with" block? 如何用更少的代码替换多个try / except块? - How can I replace multiple try/except blocks with less code?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM