本文摘自php中文网,作者不言,侵删。
本篇文章给大家带来的内容是关于Python中all()函数和any()函数的便捷用法,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
我们可能在程序开发中会面对这样一个问题?
怎样判断一个可迭代对象中元素是否全部为真,我们的做法可能就是for..in遍历然后通过bool()函数进行判断,其实这种做法可行,但是对代码而言有些冗余,因此,给大家介绍一种极其简单的方法
内置函数all()
先看一下源码
1 2 3 4 5 6 7 | def all(*args, **kwargs): # real signature unknown
"" "
Return True if bool(x) is True for all values x in the iterable.
If the iterable is empty , return True.
"" "
pass
|
接下来我们享受一下这种方法的便捷
1 2 3 | my_list=[ 'jim' , 'rose' , '' , 'sam' ]
print (all(my_list)) #返回结果:False
print (all([]))#返回结果:True
|
python还内置了一个函数any(),用来判断其可迭代对象中是否有bool()为真的元素
源码
1 2 3 4 5 6 7 | def any(*args, **kwargs): # real signature unknown
"" "
Return True if bool(x) is True for any x in the iterable.
If the iterable is empty , return False.
"" "
pass
|
实例测验
1 2 3 | my_list=[ 'jim' , 'rose' , '' , 'sam' ]
print (any(my_list)) #返回结果:True
print (any([]))#返回结果:False
|
总结:
all()有假则假,any()有真则真
以上就是Python中all()函数和any()函数的便捷用法的详细内容,更多文章请关注木庄网络博客!!
相关阅读 >>
Python实现简单文本字符串处理的方法
Python闭包执行时值的传递方式
怎样在Python中sum求和
网络编程详细介绍
如何彻底卸载Python
Python学习法则
一篇文章带你学习Python列表
c语言和Python的区别
Python中len是什么意思
Python中index怎么用
更多相关阅读请进入《Python》频道 >>
人民邮电出版社
python入门书籍,非常畅销,超高好评,python官方公认好书。
转载请注明出处:木庄网络博客 » Python中all()函数和any()函数的便捷用法