【发布时间】:2011-06-07 19:19:35
【问题描述】:
如何检查 Python 对象是否支持迭代,也就是可迭代对象 (see definition
理想情况下,我希望函数类似于 isiterable(p_object) 返回 True 或 False(仿照 isinstance(p_object, type))。
【问题讨论】:
如何检查 Python 对象是否支持迭代,也就是可迭代对象 (see definition
理想情况下,我希望函数类似于 isiterable(p_object) 返回 True 或 False(仿照 isinstance(p_object, type))。
【问题讨论】:
您可以使用isinstance 和collections.Iterable 进行检查
>>> from collections.abc import Iterable # for python >= 3.6
>>> l = [1, 2, 3, 4]
>>> isinstance(l, Iterable)
True
注意:从 Python 3.3 开始,不推荐使用或从“collections”而不是“collections.abc”导入 ABC,在 3.9 中它将停止工作。
【讨论】:
str 也是可迭代的。因此,如果您正在考虑 tuple, list, set.. 最好只检查这 3 种类型
from collections.abc import Iterable,因为从 Python 3.3 开始不推荐从集合中导入 ABC
试试这个代码
def isiterable(p_object):
try:
it = iter(p_object)
except TypeError:
return False
return True
【讨论】:
你不“检查”。你假设。
try:
for var in some_possibly_iterable_object:
# the real work.
except TypeError:
# some_possibly_iterable_object was not actually iterable
# some other real work for non-iterable objects.
请求宽恕比请求许可更容易。
【讨论】:
if not iterable: [obj] 来断言某些东西总是可以迭代的。更有可能使代码更简洁。
TypeError,但无法区分两者。
isinstance(x, Iterable) 会更好。 (但是,在 Python 中,如果您将字符串和字节串视为“单一”值,则必须小心它们。)