檢查元素是否在 Python 元組中
當需要檢查元素是否存在於元組中時,可以使用簡單的迴圈。元組是一種不可變的資料型別。這意味著,已經定義的值不能透過訪問其索引元素而改變。如果我們嘗試改變元素,則會導致一個錯誤。它們是重要的內容,因為它們確保了只讀訪問。
以下是相同程式碼的一個演示 −
案例
my_tuple_1 = (23, 45, 12, 56, 78, 0)
print("The first tuple is : ")
print(my_tuple_1)
N = 12
print("The value of 'N' has been initialized")
my_result = False
for elem in my_tuple_1 :
if N == elem :
my_result = True
break
print("Does the tuple contain the value mentioned ?")
print(my_result)輸出
The first tuple is : (23, 45, 12, 56, 78, 0) The value of 'N' has been initialized Does the tuple contain the value mentioned ? True
說明
- 定義一個元組,並在控制檯上顯示。
- 初始化 'N' 的值。
- 迴圈進行迭代,如果元素 'N' 存在於元組中,則分配一個值 'True'。
- 該值被分配給一個結果。
- 它在控制檯上顯示為輸出。
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
JavaScript
PHP