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

Python: เพิ่มขอบ (Border) ให้ Matrix แบบกำหนดเอง

บทนำ

โปรแกรมสาธิตการพิมพ์ matrix (list of lists) พร้อมขอบ (border) ที่กำหนดเอง โดยใช้ string concatenation ในลูป

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


my_list = [[2, 5, 5], [2, 7, 5], [4, 5, 1], [1, 6, 6]]
print("Matrix ต้นทาง:")
for row in my_list:
    print(row)

border = "|"

print("\nMatrix พร้อมขอบ:")
for row in my_list:
    line = border + " "
    for elem in row:
        line += str(elem) + " "
    line += border
    print(line)

ผลลัพธ์


Matrix ต้นทาง:
[2, 5, 5]
[2, 7, 5]
[4, 5, 1]
[1, 6, 6]

Matrix พร้อมขอบ:
| 2 5 5 |
| 2 7 5 |
| 4 5 1 |
| 1 6 6 |

เวอร์ชันปรับปรุง: รองรับการจัดตำแหน่ง (Alignment)


def print_matrix_with_border(matrix, border_char="|", padding=1, align="right"):
    """พิมพ์ matrix พร้อมขอบ และจัดตำแหน่งตัวเลข"""
    if not matrix:
        return
    
    # หาความกว้างสูงสุดของแต่ละคอลัมน์
    col_widths = [
        max(len(str(row[i])) for row in matrix)
        for i in range(len(matrix[0]))
    ]
    
    # ฟังก์ชันจัดรูปแบบเซลล์
    def format_cell(val, width):
        s = str(val)
        if align == "right":
            return s.rjust(width)
        elif align == "left":
            return s.ljust(width)
        else:  # center
            return s.center(width)
    
    # พิมพ์แต่ละแถว
    for row in matrix:
        cells = [format_cell(val, col_widths[i]) for i, val in enumerate(row)]
        line = border_char + " " + " ".join(cells) + " " + border_char
        print(line)

# ทดสอบ
matrix = [
    [2, 5, 5],
    [2, 7, 5],
    [4, 5, 1],
    [1, 6, 6],
    [100, 2000, 30]
]

print("ชิดขวา (default):")
print_matrix_with_border(matrix, "|", 1, "right")

print("\nชิดซ้าย:")
print_matrix_with_border(matrix, "|", 1, "left")

print("\nกึ่งกลาง:")
print_matrix_with_border(matrix, "#", 2, "center")

ผลลัพธ์เวอร์ชันปรับปรุง


ชิดขวา (default):
|   2    5    5 |
|   2    7    5 |
|   4    5    1 |
|   1    6    6 |
| 100 2000   30 |

ชิดซ้าย:
| 2     5     5     |
| 2     7     5     |
| 4     5     1     |
| 1     6     6     |
| 100   2000  30    |

กึ่งกลาง:
#   2     5     5   #
#   2     7     5   #
#   4     5     1   #
#   1     6     6   #
# 100  2000   30   #

ใช้ tabulate library (แนะนำสำหรับ production)


# pip install tabulate
from tabulate import tabulate

print(tabulate(matrix, tablefmt="grid"))
print(tabulate(matrix, tablefmt="fancy_grid"))
print(tabulate(matrix, tablefmt="pipe"))

สรุป

โค้ดพื้นฐานใช้ string concatenation ในลูป สำหรับ production ควรใช้ str.join(), str.format(), f-strings หรือ library tabulate ที่รองรับ alignment, padding, และรูปแบบตารางหลากหลาย