首页 > 文章列表 > 如何在Python中检查一个对象是否可迭代?

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

Python 可迭代对象 检查
195 2023-09-03

可迭代对象是可以使用循环或可迭代函数迭代其所有元素的对象。列表、字符串、字典、元组等都称为可迭代对象。

在 Python 语言中,有多种方法可以检查对象是否可迭代。让我们一一看看。

使用循环

在Python中,我们有两种循环技术,一种是使用“for”循环,另一种是使用“while”循环。使用这两个循环中的任何一个,我们可以检查给定的对象是否可迭代。

示例

在这个例子中,我们将尝试使用“for”循环迭代一个对象并检查它是否被迭代。以下是代码。

l = ["apple",22,"orange",34,"abc",0.3]
try:
   for i in l:
      print(i)
   print("Given object is iterable")
except TypeError:
   print("Given object is not iterable")

输出

apple
22
orange
34
abc
0.3
Given object is iterable

示例

让我们看另一个示例,使用 for 循环检查给定对象是否可迭代。

integer = 23454
try:
   for i in integer:
      print(i)
   print("Given object is iterable")
except TypeError:
   print("Given object is not iterable")

输出

以下是检查给定对象是否可迭代的代码的输出。

Given object is not iterable

使用 iter() 方法

Python 中有一个名为 iter() 的函数,它检查给定的对象是否可迭代。

示例

在这个例子中,我们将要迭代的对象和iter类传递给hasattr()函数的函数。然后,使用 iter() 方法检查该对象是否被迭代。

integer = 23454
if hasattr(integer, '__iter__'):
    my_iter = iter(integer)
    print("Given object is iterable")
else:
    print("Given object is not iterable")

输出

Given object is not iterable

使用collections.abc模块

在Python中,collections.abc模块提供了名为Iterable的抽象类,可以用来检查对象是否可迭代。

示例

在这里,当我们想要检查给定的对象是否可迭代时,我们必须将对象和“Iterable”抽象类作为参数传递给 isinstance() 函数。

from collections.abc import Iterable
integer = 23454
if isinstance(integer, Iterable):
    print("Given object is iterable")
else:	
    print("Given object is not iterable")

输出

以下是生成的输出 -

Given object is not iterable

示例

让我们再看一个示例来检查给定对象是否可迭代。

from collections.abc import Iterable
dic = {"name":["Java","Python","C","COBAL"],"Strength":[10,200,40,50,3]}
if isinstance(dic, Iterable):
    print("Given object is iterable")
else:
    print("Given object is not iterable")

输出

上述程序的输出显示为 -

Given object is iterable

使用 try 和 except

Python 中有“try”和“ except”,它们会处理发生的错误。这些还检查给定对象是否可迭代。

示例

这是一个使用 iter() 函数以及 try 和 except 来检查给定对象是否可迭代的示例。

dic = {"name":["Java","Python","C","COBAL"],"Strength":[10,200,40,50,3]}
try:
    iter(dic)
    print('Given object is iterable')
except TypeError:
    print('Given object is not iterable')

输出

Given object is iterable