【问题标题】:How to check if an object is iterable in Python? [duplicate]如何检查一个对象在 Python 中是否可迭代? [复制]
【发布时间】:2011-06-07 19:19:35
【问题描述】:

如何检查 Python 对象是否支持迭代,也就是可迭代对象 (see definition

理想情况下,我希望函数类似于 isiterable(p_object) 返回 True 或 False(仿照 isinstance(p_object, type))。

【问题讨论】:

    标签: python iterable


    【解决方案1】:

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

    【讨论】:

    • 这仅适用于新式类并且需要 Python 2.6+。
    • 请注意str 也是可迭代的。因此,如果您正在考虑 tuple, list, set.. 最好只检查这 3 种类型
    • 使用from collections.abc import Iterable,因为从 Python 3.3 开始不推荐从集合中导入 ABC
    【解决方案2】:

    试试这个代码

    def isiterable(p_object):
        try:
            it = iter(p_object)
        except TypeError: 
            return False
        return True
    

    【讨论】:

      【解决方案3】:

      你不“检查”。你假设。

      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,但无法区分两者。
      • @WillS 当然,我也是这样做的。这允许您创建允许参数可以是唯一对象或一组对象的函数。
      • 人们普遍认为不应在非异常(预期)情况下使用异常。因此,对于像函数这样的函数,其参数可能是单个值或值的集合,从这个角度来看,isinstance(x, Iterable) 会更好。 (但是,在 Python 中,如果您将字符串和字节串视为“单一”值,则必须小心它们。)
      猜你喜欢
      • 2011-03-02
      • 2019-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-05
      • 2013-11-24
      • 1970-01-01
      • 2010-12-29
      相关资源
      最近更新 更多