在 Python 的元組中檢查特定資料型別
如果需要檢查元組中特定資料型別的順序,可以使用“isinstance”方法和“鏈式if”。
“isinstance”方法檢查給定引數是否屬於特定資料型別。
“鏈式if”是一種鏈式條件語句。它是一種編寫巢狀選擇語句的不同方式。從本質上講,這意味著使用“and”運算子組合多個if語句,並對其結果進行評估。
列表可用於儲存異構值(即任何資料型別的資料,例如整數、浮點數、字串等)。
以下是同樣的演示 -
示例
my_tuple = ('Hi', ['there', 'Will'], 67)
print("The tuple is : ")
print(my_tuple)
my_result = isinstance(my_tuple, tuple) and isinstance(my_tuple[0], str) and
isinstance(my_tuple[1], list) and isinstance(my_tuple[2], int)
print("Do all instances match the required data type in the same order ? ")
print(my_result)輸出
The tuple is :
('Hi', ['there', 'Will'], 67)
Do all instances match the required data type in the same order ?
True說明
- 定義了一個列表元組,並顯示在控制檯。
- “isinstance”方法用於檢查元組中的元素是否屬於某個資料型別。
- 這是元組列表中的所有元素都執行的操作,因此使用“and”運算子連結操作。
- 它被分配給一個值。
- 它顯示在控制檯。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP