2024-05-14 19:39:16 发布
网友
Possible Duplicate:In Python, how do I determine if an object is iterable?
如何检查Python对象是否支持迭代,即iterable对象(see definition)
理想情况下,我希望函数类似于isiterable(p_object)返回True或False(在isinstance(p_object, type)之后建模)。
isiterable(p_object)
isinstance(p_object, type)
尝试此代码
def isiterable(p_object): try: it = iter(p_object) except TypeError: return False return True
你不“检查”。你假设。
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.
请求原谅比请求允许容易。
您可以使用isinstance和collections.Iterable检查这个
isinstance
collections.Iterable
>>> from collections import Iterable >>> l = [1, 2, 3, 4] >>> isinstance(l, Iterable) True
尝试此代码
你不“检查”。你假设。
请求原谅比请求允许容易。
您可以使用
isinstance
和collections.Iterable
检查这个相关问题 更多 >
编程相关推荐