有没有像isiterable这样的方法?到目前为止,我找到的唯一解决办法就是打电话
hasattr(myObj, '__iter__')
但我不确定这是否万无一失。
有没有像isiterable这样的方法?到目前为止,我找到的唯一解决办法就是打电话
hasattr(myObj, '__iter__')
但我不确定这是否万无一失。
当前回答
在我的代码中,我用来检查非可迭代对象:
hasattr (myobject, __trunc__’)
这非常快,也可以用来检查可迭代对象(使用not)。
我不是100%确定这个解决方案是否适用于所有对象,也许其他可以提供一些更多的背景。__trunc__方法与数值类型相关(所有可以舍入为整数的对象都需要它)。但是我没有发现任何包含__trunc__和__iter__或__getitem__的对象。
其他回答
如果object是可迭代的,下面代码中的isiterable函数将返回True。如果不是iterable则返回False
def isiterable(object_):
return hasattr(type(object_), "__iter__")
例子
fruits = ("apple", "banana", "peach")
isiterable(fruits) # returns True
num = 345
isiterable(num) # returns False
isiterable(str) # returns False because str type is type class and it's not iterable.
hello = "hello dude !"
isiterable(hello) # returns True because as you know string objects are iterable
Duck typing
try:
iterator = iter(the_element)
except TypeError:
# not iterable
else:
# iterable
# for obj in iterator:
# pass
类型检查
使用抽象基类。它们至少需要Python 2.6,并且只适用于新样式的类。
from collections.abc import Iterable # import directly from collections for Python < 3.3
if isinstance(the_element, Iterable):
# iterable
else:
# not iterable
然而,iter()更可靠一些,如文档所述:
检查isinstance(obj, Iterable)检测类 注册为Iterable或具有__iter__()方法,但是 它不会检测使用__getitem__()迭代的类 方法。唯一可靠的方法来确定一个对象是否 Is iterable调用iter(obj)。
有很多方法来检查一个对象是否可迭代:
from collections.abc import Iterable
myobject = 'Roster'
if isinstance(myobject , Iterable):
print(f"{myobject } is iterable")
else:
print(f"strong text{myobject } is not iterable")
Pandas有这样一个内置功能:
from pandas.util.testing import isiterable
在我的脚本中,我经常发现定义一个可迭代函数很方便。 (现在合并了Alfe建议的简化):
import collections
def iterable(obj):
return isinstance(obj, collections.Iterable):
因此,您可以测试任何对象是否具有非常可读的可迭代形式
if iterable(obj):
# act on iterable
else:
# not iterable
就像你对可调用函数所做的那样
编辑:如果你安装了numpy,你可以简单地做: 简单地说是什么
def iterable(obj):
try: iter(obj)
except: return False
return True
如果没有numpy,可以简单地实现这段代码或上面的代码。