檢查元組和列表在 Python 中是否相同
當需要檢查元組和列表是否相同時,可以使用一個簡單的迴圈,即它們包含相同的元素。
可以使用列表來儲存異構值(即任何資料型別的資料,如整數、浮點數、字串等)。
以下是對此進行演示 −
示例
my_tuple_1 = ('Hi' , 'there', 'Will') my_list = ['How' ,'are' ,'you'] print("The tuple is : ") print(my_tuple_1) print("The list is : ") print(my_list) my_result = True for i in range(0, len(my_list)): if(my_list[i] != my_tuple_1[i]): my_result = False break print("Are the tuple and list identical ? ") print(my_result)
輸出
The tuple is : ('Hi', 'there', 'Will') The list is : ['How', 'are', 'you'] Are the tuple and list identical ? False
說明
- 元組和列表在控制檯上定義並顯示。
- 將“True”值分配給一個變數。
- 將遍歷列表,並比較列表和元組中的每個元素。
- 如果不是相同的,則先前被分配“True”的變數將被分配“False”值。
- 它將跳出迴圈。
- 最終結果是儲存在變數中的布林值。
- 它顯示在控制檯上
廣告