如何在 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
廣告