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,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).

相关文章

功能概要:(目前已实现功能)公共展示部分:1.网站首页展示...
大体上把Python中的数据类型分为如下几类: Number(数字) ...
开发之前第一步,就是构造整个的项目结构。这就好比作一幅画...
源码编译方式安装Apache首先下载Apache源码压缩包,地址为ht...
前面说完了此项目的创建及数据模型设计的过程。如果未看过,...
python中常用的写爬虫的库有urllib2、requests,对于大多数比...