32

如何检查 Python 对象是否支持迭代,也就是可迭代对象(见定义

理想情况下,我想要类似于isiterable(p_object)返回 True 或 False 的函数(以 为模型isinstance(p_object, type))。

4

3 回答 3

86

您可以使用isinstancecollections.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 中它将停止工作。

于 2011-01-12T12:14:05.063 回答
10

试试这个代码

def isiterable(p_object):
    try:
        it = iter(p_object)
    except TypeError: 
        return False
    return True
于 2011-01-12T12:17:26.673 回答
4

你不“检查”。你假设。

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.

请求宽恕比请求许可更容易。

于 2011-01-12T12:20:04.417 回答