简体   繁体   English

除了python之外编写嵌套try的更好方法

[英]Better way to write nested try except python

Is there a better way for me to write this without nesting it like this?有没有更好的方法来写这个而不像这样嵌套?

try:
    if find_path(graph, startPos, (targetX+1,targetY,targetX,targetY)):
        print('YES')
except:
    try:
        if find_path(graph, startPos, (targetX,targetY+1,targetX,targetY)):
            print('YES')
    except:
        try:
            if find_path(graph, startPos, (targetX-1,targetY,targetX,targetY)):
                print('YES')
        except:
            try:
                if find_path(graph, startPos, (targetX,targetY-1,targetX,targetY)):
                    print('YES')
            except:
                print('NO')

You could make a list of potential coordinates, and then try them each in turn, in a for loop, breaking the loop on success:您可以列出潜在坐标,然后在 for 循环中依次尝试每个坐标,成功时打破循环:

success = "NO"
coords = ((targetX+1,targetY), (targetX,targetY+1), (targetX-1,targetY), (targetX,targetY-1))

for coord in coords:
    try:
        x, y = coord
        find_path(graph, startPos, (x, y, targetX,targetY))
    except:
        pass
    else:
        # Set success state and break out of the for loop
        success = "YES"
        break
print(success)

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM