python中內置函數any()與all()的用法


python中內建函數all()和any()的區別

原文:https://blog.csdn.net/quanqxj/article/details/78531856

all(x) 是針對x對象的元素而言,如果all(x)參數x對象的所有元素不為0、”、False或者x為空對象,則返回True,否則返回False 
如:

In [25]: all(['a', 'b', 'c', 'd'])  #列表list,元素都不為空或0
Out[25]: True

In [26]: all(['a', 'b', '', 'd'])  #列表list,存在一個為空的元素
Out[26]: False

In [27]: all([0, 1,2, 3])  #列表list,存在一個為0的元素
Out[27]: False

In [28]: all(('a', 'b', 'c', 'd'))  #元組tuple,元素都不為空或0
Out[28]: True

In [29]: all(('a', 'b', '', 'd'))  #元組tuple,存在一個為空的元素
Out[29]: False

In [30]: all((0, 1,2, 3))  #元組tuple,存在一個為0的元素
Out[30]: False

In [31]: all([]) # 空列表
Out[31]: True

In [32]:  all(()) # 空元組
Out[32]: True

any(x)是判斷x對象是否為空對象,如果都為空、0、false,則返回false,如果不都為空、0、false,則返回true

In [33]: any(['a', 'b', 'c', 'd'])  #列表list,元素都不為空或0
Out[33]: True

In [34]: any(['a', 'b', '', 'd'])  #列表list,存在一個為空的元素
Out[34]: True

In [35]: any((0,1))  #元組tuple,存在一個為空的元素
Out[35]: True

In [36]: any((0,''))  #元組tuple,元素都為空
Out[36]: False

In [37]:  any(()) # 空元組
Out[37]: False

In [38]: any([]) # 空列表
Out[38]: False

 區別:

q = [0]
while any(q):
    q.pop()
print(q)
# after while loop, the q is [0] still.

q = [0,1,2]
while any(q):
    # print(q, sep='', end='')
    q.pop()
print(q)
# after while loop, the q is [0].


q = [None] * 8
while any(q):
    q.pop()
print(q)
# after while loop, the q is [None, None, None, None, None, None, None, None]



q = [0]
while q:
    q.pop()
print(q)
# after while loop, the q is []


q = [None] * 8
while q:
    q.pop()
print(q)
# after while loop, the q is []

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM