Python表格打印案例有哪些?

wen python案例 4

本文目录导读:

  1. 基础文本对齐打印(不用第三方库)
  2. 使用 tabulate 库(最推荐)
  3. 使用 prettytable
  4. 使用 pandas 展示 DataFrame
  5. 使用 rich 库(终端美化)
  6. 实际业务场景案例
  7. 总结:如何选择?

Python 表格打印是一个非常常见的需求,主要有以下几个经典案例和技术方案,从简单到复杂排列:

基础文本对齐打印(不用第三方库)

案例:嵌套列表对齐

# 数据
data = [
    ["Name", "Age", "City", "Score"],
    ["Alice", "28", "New York", "95.5"],
    ["Bob", "25", "Los Angeles", "87.0"],
    ["Charlie", "32", "Chicago", "92.3"],
    ["David", "22", "San Francisco", "78.8"]
]
# 手动计算每列最大宽度
col_widths = []
for col_idx in range(len(data[0])):
    max_width = max(len(str(row[col_idx])) for row in data)
    col_widths.append(max_width)
# 打印表格
for row in data:
    formatted = " | ".join(
        str(cell).ljust(width) 
        for cell, width in zip(row, col_widths)
    )
    print(formatted)
    if row == data[0]:  # 表头下划分割线
        print("-" * len(formatted))

输出:

Name    | Age | City          | Score
--------|-----|---------------|------
Alice   | 28  | New York      | 95.5
Bob     | 25  | Los Angeles   | 87.0
Charlie | 32  | Chicago       | 92.3
David   | 22  | San Francisco | 78.8

使用 tabulate 库(最推荐)

安装:pip install tabulate

案例1:各种格式输出

from tabulate import tabulate
table = [
    ["Python", 1991, "Guido van Rossum"],
    ["Java", 1995, "James Gosling"],
    ["JavaScript", 1995, "Brendan Eich"],
    ["Go", 2009, "Robert Griesemer"]
]
headers = ["Language", "Year", "Creator"]
# 不同格式
print("简单表格:")
print(tabulate(table, headers=headers, tablefmt="simple"))
print("\n网格表格:")
print(tabulate(table, headers=headers, tablefmt="grid"))
print("\nMarkdown表格:")
print(tabulate(table, headers=headers, tablefmt="github"))
print("\nExcel友好表格:")
print(tabulate(table, headers=headers, tablefmt="plain"))
print("\n美化表格:")
print(tabulate(table, headers=headers, tablefmt="fancy_grid"))

输出示例(部分):

# simple格式:
Language      Year  Creator
----------  ------  -----------------
Python        1991  Guido van Rossum
Java          1995  James Gosling
JavaScript    1995  Brendan Eich
Go            2009  Robert Griesemer
# fancy_grid格式:
╒════════════╤════════╤═════════════════════╕
│ Language   │   Year │ Creator             │
╞════════════╪════════╪═════════════════════╡
│ Python     │   1991 │ Guido van Rossum    │
├────────────┼────────┼─────────────────────┤
│ Java       │   1995 │ James Gosling       │
├────────────┼────────┼─────────────────────┤
│ JavaScript │   1995 │ Brendan Eich        │
├────────────┼────────┼─────────────────────┤
│ Go         │   2009 │ Robert Griesemer    │
╘════════════╧════════╧═════════════════════╘

案例2:数字对齐、缺失值处理

from tabulate import tabulate
data = [
    ["Alice", 25, 3500.5],
    ["Bob", None, 4200.0],  # 缺失年龄
    ["Charlie", 30, None],  # 缺失薪资
]
headers = ["Name", "Age", "Salary"]
print(tabulate(data, headers=headers, 
               numalign="right", stralign="center",
               missingval="N/A"))
# 输出:
#   Name    Age    Salary
# -------  ----  --------
#  Alice     25    3500.5
#   Bob     N/A      4200
# Charlie    30       N/A

使用 prettytable

安装:pip install prettytable

案例:自定义样式和排序

from prettytable import PrettyTable
# 创建表格
pt = PrettyTable()
pt.field_names = ["City", "Population", "Area (km²)"]
pt.add_row(["Tokyo", 37400068, 2194])
pt.add_row(["Delhi", 28514000, 1484])
pt.add_row(["Shanghai", 25582000, 6341])
pt.add_row(["São Paulo", 21650000, 1521])
# 设置样式
pt.align["City"] = "l"      # 左对齐
pt.align["Population"] = "r" # 右对齐
pt.sortby = "Population"     # 按人口排序
pt.reversesort = True        # 降序
print("排序后的表格:")
print(pt)
# 添加颜色
pt = PrettyTable()
pt.field_names = ["Fruit", "Price", "Stock"]
pt.add_row(["Apple", 5.5, 100])
pt.add_row(["Banana", 2.3, 150])
pt.add_row(["Cherry", 8.9, 50])
print("\n默认表格:")
print(pt)

使用 pandas 展示 DataFrame

案例:DataFrame 表格显示

import pandas as pd
# 创建 DataFrame
df = pd.DataFrame({
    "Name": ["Alice", "Bob", "Charlie", "Diana"],
    "Department": ["Engineering", "Marketing", "Engineering", "HR"],
    "Salary": [90000, 75000, 95000, 65000],
    "Joining Year": [2018, 2020, 2019, 2021]
})
# 默认显示
print("默认显示:")
print(df)
print()
# 定制显示设置
pd.set_option('display.width', 100)
pd.set_option('display.max_columns', 10)
pd.set_option('display.colheader_justify', 'center')
print("定制显示:")
print(df.to_string(index=False))  # 不显示索引
print()
# 导出为 Markdown
print("Markdown 格式:")
print(df.to_markdown())

使用 rich 库(终端美化)

安装:pip install rich

案例:带颜色和样式的表格

from rich.console import Console
from rich.table import Table
console = Console()
# 创建表格
table = Table(title="程序员排行榜")
# 添加列(带样式)
table.add_column("排名", style="cyan", justify="center")
table.add_column("姓名", style="green")
table.add_column("语言", style="yellow")
table.add_column("⭐ 星星数", justify="right", style="red")
# 添加行
table.add_row("1", "John Doe", "Python", "15000")
table.add_row("2", "Jane Smith", "JavaScript", "12000")
table.add_row("3", "Bob Wilson", "Rust", "8500")
table.add_row("4", "Alice Brown", "Go", "7200")
# 显示
console.print(table)

实际业务场景案例

案例:商品库存查询系统

from tabulate import tabulate
import json
# 模拟商品数据
inventory = [
    {"id": "A001", "name": "机械键盘", "price": 299.00, "stock": 50, "category": "外设"},
    {"id": "A002", "name": "电竞鼠标", "price": 159.00, "stock": 120, "category": "外设"},
    {"id": "B001", "name": "27寸显示器", "price": 1499.00, "stock": 30, "category": "显示"},
    {"id": "B002", "name": "34寸曲面屏", "price": 2999.00, "stock": 15, "category": "显示"},
    {"id": "C001", "name": "USB-C扩展坞", "price": 89.00, "stock": 200, "category": "配件"},
]
def print_products(products, title="商品列表"):
    """格式化打印商品列表"""
    headers = ["编号", "商品名称", "价格(元)", "库存", "分类"]
    table_data = []
    for p in products:
        stock_str = f"[red]{p['stock']}[/]" if p['stock'] < 50 else str(p['stock'])
        table_data.append([
            p['id'], p['name'], 
            f"¥{p['price']:.2f}",
            stock_str,
            p['category']
        ])
    print(f"\n📦 {title}")
    print(tabulate(table_data, headers=headers, tablefmt="grid", 
                   colalign=("center", "left", "right", "right", "left")))
    # 统计信息
    total_value = sum(p['price'] * p['stock'] for p in products)
    low_stock = sum(1 for p in products if p['stock'] < 50)
    print(f"\n总计: {len(products)}件商品 | 库存总值: ¥{total_value:.2f} | 低库存警告: {low_stock}件")
# 使用
print_products(inventory, "🖥️ 商品库存报表")
# 筛选分类显示
print("\n--- 按分类筛选 ---")
for cat in set(p['category'] for p in inventory):
    filtered = [p for p in inventory if p['category'] == cat]
    print_products(filtered, f"{cat}分类")

如何选择?

场景 推荐方案
简单文本打印 自己写格式化代码
命令行工具 tabulateprettytable
数据分析 pandas DataFrame
终端美化、日志 rich 表格
Markdown/HTML导出 tabulatepandas.to_markdown()
需要排序、筛选 prettytable
Web展示 pandas + Flask/Django

我的建议:日常开发推荐使用 tabulate,因为它:

  • 零依赖(内置库)
  • 支持多种格式(控制台/Markdown/HTML/LaTeX)
  • API 简洁
  • 对中文支持良好

需要我详细演示某个特定场景的代码吗?

标签: print() \ format()

抱歉,评论功能暂时关闭!