可能重复:
In Python, how do I determine if an object is iterable?
如何检查Python对象是否支持迭代,a.k.a是可迭代对象(see definition
理想情况下,我希望函数类似于isiterable(p_object)
返回True或False(在isinstance(p_object, type)
之后建模)。
答案 0 :(得分:60)
您可以使用isinstance
和collections.Iterable
>>> from collections import Iterable
>>> l = [1, 2, 3, 4]
>>> isinstance(l, Iterable)
True
答案 1 :(得分:7)
你没有“检查”。你假设。
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.
请求宽恕比要求许可更容易。
答案 2 :(得分:4)
试试此代码
def isiterable(p_object):
try:
it = iter(p_object)
except TypeError:
return False
return True