如何在 Python 中检查对象是否可迭代?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4668621/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 16:50:36  来源:igfitidea点击:

How to check if an object is iterable in Python?

pythoniterable

提问by Boaz

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

如何检查 Python 对象是否支持迭代,又名可迭代对象(见定义

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

理想情况下,我想要类似于isiterable(p_object)返回 True 或 False 的功能(在 之后建模isinstance(p_object, type))。

回答by user225312

You can check for this using isinstanceand collections.Iterable

您可以使用isinstancecollections.Iterable

>>> from collections import Iterable
>>> l = [1, 2, 3, 4]
>>> isinstance(l, Iterable)
True

回答by Xavier Barbosa

Try this code

试试这个代码

def isiterable(p_object):
    try:
        it = iter(p_object)
    except TypeError: 
        return False
    return True

回答by S.Lott

You don't "check". You assume.

你不“检查”。你假设。

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.

It's easier to ask forgiveness than to ask permission.

请求宽恕比请求许可容易。