Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 我们如何知道一个项目是否可以被迭代_Python_Python 3.x - Fatal编程技术网

Python 我们如何知道一个项目是否可以被迭代

Python 我们如何知道一个项目是否可以被迭代,python,python-3.x,Python,Python 3.x,我读了一些关于这方面的非常古老的答案(10年),他们说在Python2.x中,这种迭代质量只是假设的 但是像3.9这样的现代python呢?我可以假设一个项目和对象可以被迭代吗 Abi全新的打字模块正是为了实现这一点。它包含所有类型 from typing import Iterable isinstance([], Iterable) # True isinstance(None, Iterable) # False 请参考下面的代码并传递您的对象,以确定它是否可编辑 def可视(obj):

我读了一些关于这方面的非常古老的答案(10年),他们说在Python2.x中,这种迭代质量只是假设的

但是像3.9这样的现代python呢?我可以假设一个项目和对象可以被迭代吗


Abi

全新的
打字模块正是为了实现这一点。它包含所有类型

from typing import Iterable
isinstance([], Iterable) # True
isinstance(None, Iterable) # False

请参考下面的代码并传递您的对象,以确定它是否可编辑

def可视(obj):
尝试:
iter(obj)
返回真值
除类型错误外:
返回错误

你好

可能不是最好的方法,但是任何具有
\uuu iter\uuu
方法的对象都是在
键入时询问和回答的迭代的很好的候选对象,不存在运行时检查。较旧的
collections.abc
为此而存在,例如
collections.abc.Iterable
。基于文档,我们不应该对iterables使用
isinstance
,因为旧式Iterable不由它标识。看来@Prince answer是推荐的方式。