Python——檢查元組中是否包含任何列表元素
當需要檢查元組中是否包含任何列表元素時,需使用布林值和簡單迭代。
下面是該演算法的演示:
示例
my_tuple = (14, 35, 27, 99, 23, 89,11) print("The tuple is :") print(my_tuple) my_list = [16, 27, 88, 99] print("The list is :") print(my_list) my_result = False for element in my_list: if element in my_tuple : my_result = True break print("The result is :") if(my_result == True): print("The element is present in the tuple") else: print("The element isn't present in the tuple")
輸出
The tuple is : (14, 35, 27, 99, 23, 89, 11) The list is : [16, 27, 88, 99] The result is : The element is present in the tuple
說明
定義一個整數元組,並在控制檯上顯示。
定義一個整數列表,並在控制檯上顯示。
最初將布林值指定為“False”。
迭代列表,如果元組中存在該元素,則將布林值重新初始化為“True”。
控制跳出迴圈。
根據布林變數的值,在控制檯上顯示輸出。
廣告