python – 找出哪个条件打破了逻辑和表达式

我想找到一种优雅的方法来获取下面的逻辑和表达式的组件,如果if块没有被执行则负责.

if test1(value) and test2(value) and test3(value):
   print 'Yeeaah'
else:
   print 'Oh, no!', 'Who is the first function that return false?'

如果输入了else块,如何通过返回第一个假值来确定test1,test2或test3是否负责?

齐射.

最佳答案 您可以使用next和生成器表达式:

breaker = next((test.__name__ for test in (test1, test2, test3) if not test(value)), None)

演示:

>>> def test1(value): return True
>>> def test2(value): return False
>>> def test3(value): return True
>>> value = '_' # irrelevant for this demo
>>>
>>> tests = (test1, test2, test3)
>>> breaker = next((test.__name__ for test in tests if not test(value)), None)
>>> breaker
'test2'
>>> if not breaker:
...:    print('Yeeaah')
...:else:
...:    print('Oh no!')
...:    
Oh no!

请注意,此代码中从不调用test3.

(超级角落情况:如果断路器不是无效,如果没有断路器则使用如果由于原因我无法理解恶作剧者将函数的__name__属性重新分配给”.)

〜编辑〜

如果你想知道第一次,第二次或第n次测试是否返回了一些有效的东西,你可以使用枚举的类似生成器表达式.

>>> breaker = next((i for i, test in enumerate(tests, 1) if not test(value)), None)
>>> breaker
2

如果要从零开始计数,请使用枚举(tests)并检查断路器是否为None,以便输入if块(因为0是假的,如0).

点赞