python中all()和any()

all(iterable)

如果 iterable 的所有元素均为真值(或可迭代对象为空)则返回 True 。 等价于:

def all(iterable):
    for element in iterable:
        if not element:
            return False
    return True

 

any(iterable):

如果 iterable 的任一元素为真值则返回 True。 如果可迭代对象为空,返回 False。 等价于:

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False

 

1.那当all([])返回的是什么呢?

返回的是True

由源码得知,空列表,直接就执行了return True操作

 

 2.那any([])返回什么?

返回的是False

由源码得知,空列表,直接就执行了return False操作

 

 

补充:
元素:
'0'在python中是True,所以all('0123')、all('0')都会返回True。
- 浮点型或整型的0会返回False。
- 但all([''])返回的是False,因为['']中有一个''元素, 空字符串''在python中是False;

python中哪些元素是真True,哪些元素是假False

for elenment in ['', [], (), {}, 'S', [1, 2], (1, 2), {3, 'SS'}, [''], 0, 0.0, '0', 1, 2, None]:
    if elenment:
        print(elenment, '%10s' % '---', True) 
    else:
        print(elenment, '%10s' % '---', False) 
>>>          
        --- False
[]        --- False
()        --- False
{}        --- False
S        --- True
[1, 2]        --- True
(1, 2)        --- True
{3, 'SS'}        --- True
['']        --- True
0        --- False
0.0        --- False
0        --- True
1        --- True
2        --- True
None        --- False

部分参考:https://blog.csdn.net/craftsman2020/article/details/107751243

posted @ 2020-12-13 17:39  echo'coding'  阅读(255)  评论(0编辑  收藏  举报