Python – 元素級矩陣差


當需要列印元素級矩陣差時,我們要迭代列表元素並在這些值上使用 zip 方法。

示例

下面是對相同內容的演示

my_list_1 = [[3, 4, 4], [4, 3, 1], [4, 8, 3]]
my_list_2 = [[5, 4, 7], [9, 7, 5], [4, 8, 4]]
print("The first list is :")
print(my_list_1)
print("The second list is :")
print(my_list_2)

my_result = []

for sub_str_1, sub_str_2 in zip(my_list_1, my_list_2):
   temp_str = []

   for element_1, element_2 in zip(sub_str_1, sub_str_2):
      temp_str.append(element_2-element_1)
   my_result.append(temp_str)

print("The result is :")
print(my_result)

輸出

The first list is :
[[3, 4, 4], [4, 3, 1], [4, 8, 3]]
The second list is :
[[5, 4, 7], [9, 7, 5], [4, 8, 4]]
The result is :
[[2, 0, 3], [5, 4, 4], [0, 0, 1]]

說明

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

  • 已建立一個空列表。

  • 使用 zip 方法對兩個列表列表進行壓縮並進行迭代。

  • 在“for”迴圈內,建立了一個空列表,並將列表列表的元素追加到列表中。

  • 在此之外,該列表被追加到另一個列表中。

  • 這將作為輸出顯示在控制檯上。

更新於:2021 年 9 月 20 日

213 次瀏覽

開啟您的事業

完成課程並獲得認證

立即開始
廣告
© . All rights reserved.