在 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”運算子連結操作。
  • 它被分配給一個值。
  • 它顯示在控制檯。

更新於: 12-Mar-2021

363 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.