How to check if an object is iterable in Python?
本问题已经有最佳答案,请猛点这里访问。
Possible Duplicate:
In Python, how do I determine if an object is iterable?
如何检查一个python对象是否支持迭代,也就是说一个iterable对象(参见定义
理想情况下,我希望函数类似于
你可以用
1 2 3 4 | >>> from collections import Iterable >>> l = [1, 2, 3, 4] >>> isinstance(l, Iterable) True |
你不"检查"。你假设。
1 2 3 4 5 6 | 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. |
请求宽恕比请求许可更容易。
试试这个代码
1 2 3 4 5 6 | def isiterable(p_object): try: it = iter(p_object) except TypeError: return False return True |