如何检查对象在Python中是否可迭代? [英] How to check if an object is iterable in Python?

查看:65
本文介绍了如何检查对象在Python中是否可迭代?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何检查Python对象是否支持迭代(又称为可迭代对象)(请参见定义

How does one check if a Python object supports iteration, a.k.a an iterable object (see definition

理想情况下,我希望类似于isiterable(p_object)的函数返回True或False(在isinstance(p_object, type)之后建模).

Ideally I would like function similar to isiterable(p_object) returning True or False (modelled after isinstance(p_object, type)).

推荐答案

您可以使用isinstancecollections.Iterable

>>> from collections.abc import Iterable # for python >= 3.6
>>> l = [1, 2, 3, 4]
>>> isinstance(l, Iterable)
True

注意:自Python 3.3起,不建议使用集合"而不是"collections.abc"中的ABC或从其中导入ABC,而在3.9版本中,它将停止工作.

Note: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated since Python 3.3, and in 3.9 it will stop working.

这篇关于如何检查对象在Python中是否可迭代?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆