我可以在一行中组合错误异常和条件吗?

Can I combine error exception and a conditional in a single line?

例如,如果我的代码执行如下操作:

try:
    for n in graph[x]:
        #...
        #...
        if event == 0:
            #do something
except IndexError:
        #do the same thing

我的if块和我的错误异常块具有完全相同的代码;所以我不想有多余的线,而是想把这两个块结合起来。我想做类似 except IndexError or if target == 0: 的事情作为一个条件。有什么巧妙的方法吗?

最简单,虽然有点老套:改变你的

    if event == 0:
        #do something

    if event == 0:
        raise IndexError

以便"tickle"以下except IndexError子句。

Cleaner 是将 do something 变成内部函数 defd 就在整个 try 语句之前;但在某些情况下确实需要多做一些工作。