Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Python – ลบ First Diagonal Elements จาก Square Matrix

ภาพรวม

จาก square matrix (list of lists ขนาด n x n) ให้ลบ element บน main diagonal (index i,i) ออกจากแต่ละแถว

ตัวอย่างโค้ด


my_list = [
    [45, 67, 85, 42, 11],
    [78, 99, 10, 13, 0],
    [91, 23, 23, 64, 23],
    [91, 11, 22, 14, 35]
]

print("The list is:", my_list)

my_result = []
for i, row in enumerate(my_list):
    # เก็บ element ที่ column index != row index
    new_row = [val for j, val in enumerate(row) if j != i]
    my_result.append(new_row)

print("The resultant matrix is:", my_result)

ผลลัพธ์

The list is: [[45, 67, 85, 42, 11], [78, 99, 10, 13, 0], [91, 23, 23, 64, 23], [91, 11, 22, 14, 35]]
The resultant matrix is: [[67, 85, 42, 11], [78, 10, 13, 0], [91, 23, 64, 23], [91, 11, 22, 35]]

คำอธิบาย

Row iOriginalRemove index iResult
0[45, 67, 85, 42, 11]index 0 (45)[67, 85, 42, 11]
1[78, 99, 10, 13, 0]index 1 (99)[78, 10, 13, 0]
2[91, 23, 23, 64, 23]index 2 (23)[91, 23, 64, 23]
3[91, 11, 22, 14, 35]index 3 (14)[91, 11, 22, 35]

NumPy Version (เร็วกว่าสำหรับ Matrix ใหญ่)


import numpy as np
arr = np.array(my_list)
# Boolean mask ไม่ใช่ diagonal
mask = ~np.eye(arr.shape[0], dtype=bool)
result = arr[mask].reshape(arr.shape[0], -1)
print(result)

ประยุกต์: Secondary Diagonal


# ลบ secondary diagonal (i, n-1-i)
new_row = [val for j, val in enumerate(row) if j != len(row) - 1 - i]