如何检查对象在Python中是否可迭代?
问题描述:
如何检查Python对象是否支持迭代(又称为可迭代对象)(请参见定义
How does one check if a Python object supports iteration, a.k.a an iterable object (see definition
理想情况下,我希望类似于isiterable(p_object)
的函数返回True或False(在isinstance(p_object, type)
之后建模).
Ideally I would like function similar to isiterable(p_object)
returning True or False (modelled after 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.abc"中的ABC或从其中导入ABC,而在3.9版本中,它将停止工作.
Note: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated since Python 3.3, and in 3.9 it will stop working.