ลบ Matrix สองอันแบบ Element-wise (ค่าตรงกัน Index) โดยใช้ zip() จับคู่ Row และ Element
ตัวอย่างโค้ด
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(list1, list2)จับคู่ Row ตรง Index กันzip(row1, row2)จับคู่ Element ตรง Column กัน- คำนวณ
element_2 - element_1(List 2 - List 1) - สร้าง Matrix ผลลัพธ์ขนาดเดียวกัน
- NumPy เร็วกว่า:
np.array(list2) - np.array(list1)