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”循环内,创建了一个空列表,并将列表列表的元素追加到列表中。
在此之外,该列表被追加到另一个列表中。
这将作为输出显示在控制台上。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP