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

การต่อแนวตั้งในเมทริกซ์ใน Python


เมื่อจำเป็นต้องต่อเมทริกซ์ในแนวตั้ง สามารถใช้รายการความเข้าใจได้

ด้านล่างนี้เป็นการสาธิตสิ่งเดียวกัน -

ตัวอย่าง

from itertools import zip_longest

my_list = [["Hi", "Rob"], ["how", "are"], ["you"]]

print("The list is : ")
print(my_list)

my_result = ["".join(elem) for elem in zip_longest(*my_list, fillvalue ="")]

print("The list after concatenating the column is : ")
print(my_result)

ผลลัพธ์

The list is :
[['Hi', 'Rob'], ['how', 'are'], ['you']]
The list after concatenating the column is :
['Hihowyou', 'Robare']

คำอธิบาย

  • แพ็คเกจที่จำเป็นจะถูกนำเข้า

  • มีการกำหนดรายการและแสดงบนคอนโซล

  • ความเข้าใจของรายการใช้เพื่อซิปองค์ประกอบ และรวมเข้าด้วยกันโดยกำจัดช่องว่าง

  • สิ่งนี้ถูกกำหนดให้กับตัวแปร

  • ตัวแปรนี้แสดงเป็นเอาต์พุตบนคอนโซล