檢查變數是否是 Python 中的元組


當需要檢查變數是否是元組時,可以使用“type”方法。一個元組是一個不可變的資料型別。這意味著,一旦定義了值,就不能透過訪問其索引元素來更改它們。如果我們試圖更改元素,則會導致錯誤。它們包含很重要,因為它們確保了只讀訪問。

“type”方法用於檢視作為引數傳遞給它的可迭代物件/值是什麼型別。

以下是相同的演示 −

示例

動態演示

my_tuple_1 = (7, 8, 0, 3, 45, 3, 2, 22, 4)

print ("The tuple is : " )
print(my_tuple_1)

my_result = type(my_tuple_1) is tuple

print("Is the given variable a tuple ? ")
print(my_result)

輸出

The tuple is :
(7, 8, 0, 3, 45, 3, 2, 22, 4)
Is the given variable a tuple ?
True

解釋

  • 定義一個元組,並顯示在控制檯上。
  • 檢查元組的型別,並使用“is”和“tuple”運算子來檢查它是否為元組型別。
  • 此結果被分配給一個值。
  • 它作為輸出顯示在控制檯上。

更新於: 2021 年 3 月 11 日

3K+ 瀏覽量

開啟你的職業生涯

透過完成這門課程獲得認證

開始
廣告
© . All rights reserved.