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

猜你喜欢

转载自www.cnblogs.com/zpstu/p/10160404.html