python中的all和any使用示例

分别用python2.7和3.5测过,结果是一样的,具体如下——


In [1]: a=True; b= True; c=False
In [2]: abc=(a,b,c)

In [3]: any(abc)  # 序列中只需要一个元素为True,  结果即为True
Out[3]: True

In [4]: all(abc)  # 序列中必须所有元素为True,  结果为True,但是也有例外,请看下面
Out[4]: False

In [5]: all(())  # 注意,对空序列求all()会得到True
Out[5]: True
In [6]: any(())
Out[6]: False

In [7]: all((True))
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-7-96d59bf9da00> in <module>()
----> 1 all((True))
TypeError: 'bool' object is not iterable

In [8]: all((True,)) # all(iterable_object) 只对可迭代对象(例如序列)起作用
Out[8]: True

In [9]: any((True))
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-9-01378c2303c5> in <module>()
----> 1 any((True))
TypeError: 'bool' object is not iterable

In [10]: any((True,))      # any(iterable_object) 只对可迭代对象(例如序列)起作用
Out[10]: True


In [11]: result_1 = 2<1

In [12]: result_2 = -1 > -2
In [13]: result_3 = 0
In [14]: result_4 = ""
In [15]: result_5 = []
In [16]: result_6 = ()
In [17]: group_1 = (result_1, result_2, result_3, result_4, result_5, result_6)

In [20]: all(group_1)

Out[20]: False
In [21]: any(group_1)
Out[21]: True


In [22]: group_2 = (result_3, result_4, result_5, result_6)
In [23]: for x in group_2: print (x,)
0

[]
()

In [24]: all(group_2)
Out[24]: False
In [25]: any(group_2)
Out[25]: False


In [26]: # 测试含有非零元素的序列

In [27]: test_seq = (-1,0,[])

In [28]: all(test_seq) # 结论:0、False、空序列都会被认为是“假”
Out[28]: False
In [29]: any(test_seq) # -1不在“假”的条件范围内,所以结果为真
Out[29]: True

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值