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

Transpose Matrix ใน Python: 4 วิธี (Nested Loop, List Comprehension, Zip, NumPy)

Transpose Matrix = สลับแถวเป็นคอลัมน์ คอลัมน์เป็นแถว

ตัวอย่าง

Original (3x2):
[[1, 2],
 [3, 4],
 [5, 6]]

Transposed (2x3):
[[1, 3, 5],
 [2, 4, 6]]

วิธี 1: Nested Loop (Classic)

x = [[1, 2], [3, 4], [5, 6]]
result = [[0, 0, 0], [0, 0, 0]]

for i in range(len(x)):
    for j in range(len(x[0])):
        result[j][i] = x[i][j]

for r in result:
    print(r)
# [1, 3, 5]
# [2, 4, 6]

วิธี 2: Nested List Comprehension (Pythonic)

x = [[1, 2], [3, 4], [5, 6]]
result = [[x[j][i] for j in range(len(x))] for i in range(len(x[0]))]

for r in result:
    print(r)
# [1, 3, 5]
# [2, 4, 6]

วิธี 3: zip() + unpacking (Concise)

x = [[1, 2], [3, 4], [5, 6]]
result = list(map(list, zip(*x)))
# หรือ
result = [list(row) for row in zip(*x)]

for r in result:
    print(r)
# [1, 3, 5]
# [2, 4, 6]

วิธี 4: NumPy (เร็วที่สุด สำหรับ Matrix ใหญ่)

import numpy as np

x = [[1, 2], [3, 4], [5, 6]]
print(np.transpose(x))
# [[1 3 5]
#  [2 4 6]]

# หรือ
arr = np.array(x)
print(arr.T)
# [[1 3 5]
#  [2 4 6]]

เปรียบเทียบ

Methodความเร็วMemoryDependenciesเหมาะกับ
Nested Loopช้าปานกลางไม่มีเรียนรู้ logic
List Comprehensionเร็วกว่า loopปานกลางไม่มีGeneral use
zip(*matrix)เร็วต่ำไม่มีPythonic, ไม่ต้อง import
NumPyเร็วที่สุด (C backend)ต่ำ (view)ต้องติดตั้งScientific computing, Large matrices

หมายเหตุ

  • zip(*x) หยุดที่แถวสั้นสุด (truncates) - ต้องแน่ใจว่า rectangular matrix
  • NumPy คืน ndarray ใช้ .tolist() ถ้าต้องการ list ธรรมดา