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

ต่อ Matrix แบบแนวตั้ง (Vertical Concatenation) ใน Python


เมื่อต้องการต่อคอลัมน์ของ Matrix (ลิสต์ของลิสต์) แนวตั้ง ใช้ zip_longest จาก itertools

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

from itertools import zip_longest

matrix = [["Hi", "Rob"], ["how", "are"], ["you"]]
print("Matrix:")
print(matrix)

result = [''.join(col) for col in zip_longest(*matrix, fillvalue='')]
print("Vertically concatenated:")
print(result)

ผลลัพธ์

Matrix: [['Hi', 'Rob'], ['how', 'are'], ['you']]
Vertically concatenated: ['Hihowyou', 'Robare']

คำอธิบาย

  • *matrix unpack rows ให้ zip_longest

  • zip_longest(..., fillvalue='') จับคู่คอลัมน์ แทนค่าขาดด้วย ''

  • ''.join(col) รวมสตริงในแต่ละคอลัมน์

  • คอลัมน์ 0: Hi + how + you = Hihowyou

  • คอลัมน์ 1: Rob + are + '' = Robare