How to check if an object is iterable in Python? [duplicate]

会有一股神秘感。 提交于 2019-12-03 06:50:19

问题


Possible Duplicate:
In Python, how do I determine if an object is iterable?

How does one check if a Python object supports iteration, a.k.a an iterable object (see definition

Ideally I would like function similar to isiterable(p_object) returning True or False (modelled after isinstance(p_object, type)).


回答1:


You can check for this using isinstance and collections.Iterable

>>> from collections import Iterable
>>> l = [1, 2, 3, 4]
>>> isinstance(l, Iterable)
True



回答2:


You don't "check". You assume.

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.

It's easier to ask forgiveness than to ask permission.




回答3:


Try this code

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


来源:https://stackoverflow.com/questions/4668621/how-to-check-if-an-object-is-iterable-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!