我有4个条件检查,每个都可能会或可能不会失败。但如果其中一个失败,我想知道哪个特定条件失败而不使用多个if
语句:
if (opts_vals['config_path'] is None or not os.path.isfile(opts_vals['config_path'])) or (opts_vals['myaccount'] is None or opts_vals['cust_account'] is None):
答案 0 :(得分:2)
我认为这是不可能的。你只需要重新测试你的价值观,或者用另一种方式写你的测试,也许是这样的:
if opts_vals['config_path'] not None:
if os.path.isfile(opts_vals['config_path']):
do_stuff()
else:
do_stuff_failed()
else:
do_stuff_failed()
答案 1 :(得分:1)
我不太确定多个if语句有什么问题,但您可以将比较结果分配给变量:
test1 = opts_vals['config_path'] is None
test2 = not os.path.isfile(opts_vals['config_path'])
...
然后您可以一起测试所有条件并确定哪一个失败:
if test1 or test2 or test3 or test4:
failure = [test1, test2, test3, test4].index(True)
do some other stuff
# failure contains 0 if test1 was True, or 1 if test2 was True, etc
# note if none of them was True then index would generate a ValueError