在Python中,如何确定对象是否可迭代?

有没有像isiterable这样的方法?到目前为止我找到的唯一解决方案是打电话

hasattr(myObj, '__iter__')

但我不确定这是多么万无一失.

解决方法:

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

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

iter内置检查__iter__方法,或者在字符串的情况下检查__getitem__方法.
>另一种通用的pythonic方法是假设一个可迭代的,然后如果它不能在给定的对象上工作则优雅地失败. Python词汇表:

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.

06001

> collections模块提供了一些抽象基类,它们可以询问类或实例是否提供特定功能,例如:

from collections.abc import Iterable

if isinstance(e, Iterable):
    # e is iterable

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

上一篇:6、迭代器


下一篇:python – 可以从pandas dataframe迭代