Python – 檢查特定索引中的元素是否等於列表元素


當需要檢查特定索引處的元素是否等於另一個元素列表時,可以使用簡單的迭代和布林值。

示例

以下是對此進行演示 -

my_list_1 = [69, 96, 23, 57, 13, 75, 13]
my_list_2 = [68, 21, 69, 23, 49, 35, 73]

print("The first list is : " )
print(my_list_1)

print("The first list after sorting is :")
my_list_1.sort()
print(my_list_1)

print("The second list is : " )
print(my_list_2)

print("The first list after sorting is :")
my_list_2.sort()
print(my_list_2)

check_list = [66, 89, 69]
print("The second list is : " )
print(check_list)

print("The check list after sorting is :")
check_list.sort()
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

if(my_result == True):
   print("The elements of the list are equal to the elements in the check list")
else:
   print("The elements of the list aren't equal to elements in the check list")

輸出

The first list is :
[69, 96, 23, 57, 13, 75, 13]
The first list after sorting is :
[13, 13, 23, 57, 69, 75, 96]
The second list is :
[68, 21, 69, 23, 49, 35, 73]
The first list after sorting is :
[21, 23, 35, 49, 68, 69, 73]
The second list is :
[66, 89, 69]
The check list after sorting is :
[66, 69, 89]
The elements of the list aren't equal to elements in the check list

說明

  • 定義兩個整數列表,並顯示在控制檯上。

  • 對它們進行排序並顯示在控制檯上。

  • 將布林值賦值為 True。

  • 使用“enumerate”迭代第一個列表。

  • 比較特定索引處的元素,並檢查該元素是否在第三個列表中找到。

  • 如果沒有找到,則布林值將被賦值為“False”。

  • 控制退出迴圈。

  • 根據布林值,在控制檯上顯示訊息。

更新時間:2021 年 9 月 13 日

689 次瀏覽

開啟你的 職業

完成課程獲得認證

開始
展示廣告