1. 程式人生 > >python中內建函式any()與all()的用法

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 []