Python – 測試所有行是否與其他矩陣有任何共同元素


當需要測試所有行是否與其他矩陣有任何共同元素時,可以使用簡單的迭代和標誌值。

示例

以下是相同的演示

my_list_1 = [[3, 16, 1], [2, 4], [4, 31, 31]]
my_list_2 = [[42, 16, 12], [42, 8, 12], [31, 7, 10]]

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

my_result = True

for idx in range(0, len(my_list_1)):

   temp = False

   for element in my_list_1[idx]:
      if element in my_list_2[idx]:
         temp = True
         break

   if not temp :
      my_result = False
      break

if(temp == True):
   print("The two matrices contain common elements")
else:
   print("The two matrices don't contain common elements")

輸出

The first list is :
[[3, 16, 1], [2, 4], [4, 31, 31]]
The second list is :
[[42, 16, 12], [42, 8, 12], [31, 7, 10]]
The two matrices don't contain common elements

解釋

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

  • 一個變數被設定為布林值“True”。

  • 迭代第一個列表,並將一個臨時變數設定為布林值“False”。

  • 如果該元素存在於第二個列表中,則將臨時變數設定為布林值“True”。

  • 控制跳出迴圈。

  • 如果迴圈外部的臨時變數為 False,則控制跳出迴圈。

  • 最後,根據臨時變數的值,在控制檯上顯示相關訊息。

更新於: 2021年9月14日

172 次檢視

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.