Python any()函数详细教程
any()
函数只接受一个可迭代的类型参数;如果该迭代器的任意一个元素为True
,则返回True
,否则返回False
;如果迭代器为空返回False
;
在Python中,非0
、非None
、非空的值都为True
;
A = [0,0,0,0,1] #列表可迭代
for i in A:
print(i,end=' ')
print(any(A))
输出:
0 0 0 0 1 True
迭代器为空:
A = []
for i in A:
print(i,end=' ')
print(any(A))
输出:
False
等价函数
any()
函数的实现方法等价于以下函数:
def myany(iterable):
for element in iterable:
if element:
return True
return False
错误的类型
当向any()
函数传递一个不可迭代的参数时,会造成TypeError
类型错误;
例:
print(any(1))
输出:
Traceback (most recent call last): File "C:\Users\hocn\Desktop\test.py", line 1, in <module> print(any(1)) TypeError: 'int' object is not iterable