Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Nối dọc (vertical concatenation) ma trận trong Python

Dùng itertools.zip_longest để chuyển cột thành hàng, nối chuỗi.

Ví dụ

from itertools import zip_longest

matrix = [["Hi", "Rob"], ["how", "are"], ["you"]]
print("Ma trận:", matrix)

result = ["".join(col) for col in zip_longest(*matrix, fillvalue="")]
print("Nối dọc:", result)

Kết quả

Ma trận: [['Hi', 'Rob'], ['how', 'are'], ['you']]
Nối dọc: ['Hihowyou', 'Robare']

Giải thích

  • zip_longest(*matrix, fillvalue="") lấy phần tử theo cột, thiếu thì fill chuỗi rỗng.
  • Cột 0: "Hi", "how", "you" -> "Hihowyou".
  • Cột 1: "Rob", "are", "" -> "Robare".
  • List comprehension join từng cột.
  • Ứng dụng: xoay ma trận văn bản, xử lý dữ liệu cột.