在这种情况下,这对我来说工作得很好,但它只是为代码运行增加了 4 秒的额外时间
try:
val1 = a
except:
try:
val1 = b
except:
try:
val1 = c
except:
try:
val1 = d
except:
try:
val1 = e
except:
pass
有没有更好的方法来进行多次尝试和排除?
try:
val1 = a
except (NameError, ValueError): # Handle multiple exceptions
val1 = b
except (KeyError, IndexError): # Handle other exceptions
val1 = c
except: # Catch-all for any other exception
val1 = None # Or handle it differently
for value in [a, b, c, d, e]:
try:
val1 = value
break # Exit the loop if successful
except:
pass # Continue to the next value
if val1 is None:
# Handle case where no value was assigned
value_map = {
'a': lambda: a,
'b': lambda: b,
'c': lambda: c,
'd': lambda: d,
'e': lambda: e,
}
try:
val1 = value_map[variable_containing_key]()
except KeyError:
# Handle invalid key
except Exception as e:
# Handle other exceptions