Python 如何检查对象是否可迭代
可迭代对象是指可以使用循环或可迭代函数遍历其所有元素的对象。列表、字符串、字典、元组等都被称为可迭代对象。
在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