如何检查Python对象是否支持迭代,即可迭代对象(参见定义)?
理想情况下,我想要一个类似于
理想情况下,我想要一个类似于
isinstance(p_object, type)
的函数,返回True或False,名为isiterable(p_object)
。您可以使用isinstance
和collections.Iterable
来检查这一点。
>>> from collections.abc import Iterable # for python >= 3.6
>>> l = [1, 2, 3, 4]
>>> isinstance(l, Iterable)
True
注意:自 Python 3.3 起,使用“collections”而非“collections.abc”中的 ABCs 已被弃用,并且在 3.9 中将停止工作。
尝试这段代码
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.
冒昧行事比征得许可更容易。
if not iterable: [obj]
来断言某些东西始终是可迭代的。在我看来,这样更有可能使代码更清晰。 - Will STypeError
,但无法区分两者之间的差别。 - Robert Siemerisinstance(x, Iterable)
从这个角度来看会更好。(但在 Python 中,如果您将字符串和字节串视为“单个”值,则必须小心处理。) - cjs
str
也是可迭代的。因此,如果您考虑的是tuple、list、set
,最好只检查这三种类型。 - Shaunfrom collections.abc import Iterable
导入 ABCs 已经自 Python 3.3 起被弃用。 - Tomas P