在Python中,如何确定对象是否可迭代? [英] In Python, how do I determine if an object is iterable?

查看:79
本文介绍了在Python中,如何确定对象是否可迭代?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有类似isiterable的方法?到目前为止,我发现的唯一解决方案是打电话给

Is there a method like isiterable? The only solution I have found so far is to call

hasattr(myObj, '__iter__')

但是我不确定这有多愚蠢.

But I am not sure how fool-proof this is.

推荐答案

  1. __iter__的检查适用于序列类型,但在例如字符串在Python 2中.我也想知道正确的答案,在此之前,这是一种可能性(也适用于字符串):

  1. Checking for __iter__ works on sequence types, but it would fail on e.g. strings in Python 2. I would like to know the right answer too, until then, here is one possibility (which would work on strings, too):

from __future__ import print_function

try:
    some_object_iterator = iter(some_object)
except TypeError as te:
    print(some_object, 'is not iterable')

内置的iter检查__iter__方法,如果是字符串,则检查__getitem__方法.

The iter built-in checks for the __iter__ method or in the case of strings the __getitem__ method.

另一种通用的pythonic方法是假定一个可迭代的对象,如果它不适用于给定的对象,则正常地失败. Python词汇表:

Another general pythonic approach is to assume an iterable, then fail gracefully if it does not work on the given object. The Python glossary:

Pythonic编程风格,它通过检查对象的方法或属性签名来确定对象的类型,而不是通过与某种类型对象的显式关系来确定(如果它看起来像 duck ,而像鸭子,它必须是鸭子.")通过强调接口而不是特定类型,精心设计的代码通过允许多态替换来提高其灵活性.鸭式输入避免使用type()或isinstance()进行测试. 相反,它通常采用EAFP(比授权更容易请求宽恕)风格的编程.

Pythonic programming style that determines an object's type by inspection of its method or attribute signature rather than by explicit relationship to some type object ("If it looks like a duck and quacks like a duck, it must be a duck.") By emphasizing interfaces rather than specific types, well-designed code improves its flexibility by allowing polymorphic substitution. Duck-typing avoids tests using type() or isinstance(). Instead, it typically employs the EAFP (Easier to Ask Forgiveness than Permission) style of programming.

...

try:
   _ = (e for e in my_object)
except TypeError:
   print my_object, 'is not iterable'

  • collections 模块提供了一些抽象基础类,允许询问类或实例是否提供特定功能,例如:

  • The collections module provides some abstract base classes, which allow to ask classes or instances if they provide particular functionality, for example:

    from collections.abc import Iterable
    
    if isinstance(e, Iterable):
        # e is iterable
    

    但是,这不会检查可通过__getitem__迭代的类.

    However, this does not check for classes that are iterable through __getitem__.

    这篇关于在Python中,如何确定对象是否可迭代?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆