def is_numbers(iterable):
"""Проверить все ли элементы в iterable есть числа."""
if iterable:
return all(map(lambda x: isinstance(x, (int, float, complex)), iterable))
else:
return False
如果我们只传递一个数字,则会抛出 TypeError 异常:
>>> is_numbers(131)
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
is_numbers(131)
File "/home/dzmitry/iterchk.py", line 23, in is_numbers
return all(map(lambda x: isinstance(x, (int, float, complex)), iterable))
TypeError: 'int' object is not iterable
>>>
但是如果我们传递 None,那么函数返回 False:
>>> is_numbers(None)
False
>>>
为什么会这样?
毕竟, None 似乎也不可迭代: https ://stackoverflow.com/questions/1952464/in-python-how-do-i-determine-if-an-object-is-iterable
try:
none_iterator = iter(None)
except TypeError:
print(None, 'is not iterable')
None is not iterable
>>>
一切都按照您在代码中指定的方式发生:通过
None
- 第二个分支 (else
) 被触发,它返回False
: