Python 之 any与all 方法

any()
doc: Return True if any element of the iterable is true. If the iterable is empty, return False.
只要迭代器中有一个元素为真就为真。

In [4]: a = [True, False]  
In [5]: any(a)  
Out[5]: True  

也就是说,整个迭代中返回所有的真假判断中有一个真就是真,就好像说一箱子鸡蛋中只要有一个坏了,我们就认定这厢鸡蛋坏了。


In [6]: b = ['good','bad','good','good']  
In [7]: any(i=='bad' for i in b)  
Out[7]: True  
把坏的鸡蛋扔了

In [9]: b.pop(1)  
Out[9]: 'bad'    
In [10]: any(i=='bad' for i in b)  
Out[10]: False  
结果就想法了,如果对于单个元素的判断,有点像 'bad'

all()
doc:Return True if all elements of the iterable are true (or if the iterable is empty)
也就是说,迭代器中所有的判断项返回都是真,结果才为真

In [13]: a  
Out[13]: [True, False]    
In [14]: all(a)  
Out[14]: False  
如果一箱子鸡蛋全都好,才算好。


In [15]: b  
Out[15]: ['good', 'good', 'good', 'bad']  
In [16]: all('good'== i for i in b)  
Out[16]: False  

有一个坏的,返回false

In [17]: b.pop()  
Out[17]: 'bad'  
In [18]: all('good'== i for i in b)  
Out[18]: True  
剔除不好的,全都为good,结果为True


文档地址

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值