Python – 檢查列表元素的索引是否等於列表元素
當需要檢查元素的索引是否等於列表中的元素時,使用簡單的迭代和列舉屬性。
示例
以下是同樣的一個演示 −
my_list_1 = [12, 62, 19, 79, 58, 0, 99]
my_list_2 = [12, 74, 19, 54, 58, 0, 11]
print("The first list is :")
print(my_list_1)
print("The second list is :")
print(my_list_2)
my_list_1.sort()
my_list_2.sort()
print("The first list after sorting is ")
print(my_list_1)
print("The second list after sorting is ")
print(my_list_2)
check_list = [9, 8, 2]
print("The check_list is :")
print(check_list)
my_result = True
for index, element in enumerate(my_list_1):
if my_list_1[index] != my_list_2[index] and element in check_list:
my_result = False
break
print("The result is :")
if(my_result == True):
print("The index elements is equal to the elements of the list")
else:
print("The index elements is not equal to the elements of the list")輸出
The first list is : [12, 62, 19, 79, 58, 0, 99] The second list is : [12, 74, 19, 54, 58, 0, 11] The first list after sorting is [0, 12, 19, 58, 62, 79, 99] The second list after sorting is [0, 11, 12, 19, 54, 58, 74] The check_list is : [9, 8, 2] The result is : The index elements is equal to the elements of the list
說明
定義兩個整數列表並在控制檯上顯示它們。
對它們進行排序並在控制檯上顯示。
定義另一個整數列表並在控制檯上顯示。
將一個值設為布林值 True。
使用列舉遍歷第一個列表,並比較兩個相應列表的第一個兩個元素的索引。
如果它們相等,並且此元素存在於整數列表中,則布林值將被設為 False。
控制元件從迴圈中跳出。
根據布林值,在控制檯上顯示相關訊息。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP