Python で書式付きテーブルを作成する
これまでにさまざまな配置技術を学んだので、それらを応用して書式の整ったテーブルを作成しましょう。テーブルは構造化されたデータを読みやすい形式で表示する一般的な方法であり、適切な配置は表形式の情報を効果的に提示するために重要です。
固定幅列を持つシンプルなテーブル
まずは固定幅列を使ってシンプルなテーブルを作成しましょう。
/home/labex/project
ディレクトリに simple_table.py
という名前の新しいファイルを作成します。
## simple_table.py
print("Simple Fixed-Width Table")
print("-" * 50)
## Define some data
header = ["Name", "Age", "City", "Profession"]
data = [
["John Smith", 34, "New York", "Doctor"],
["Sarah Johnson", 28, "San Francisco", "Engineer"],
["Michael Brown", 42, "Chicago", "Teacher"],
["Emily Davis", 31, "Boston", "Scientist"]
]
## Print header
print(f"{header[0]:<20} {header[1]:<8} {header[2]:<15} {header[3]:<15}")
print("-" * 60)
## Print rows
for row in data:
print(f"{row[0]:<20} {row[1]:<8} {row[2]:<15} {row[3]:<15}")
- ファイルを保存して実行します。
python3 ~/project/simple_table.py
- 以下のように書式の整ったテーブルが表示されるはずです。
Simple Fixed-Width Table
--------------------------------------------------
Name Age City Profession
------------------------------------------------------------
John Smith 34 New York Doctor
Sarah Johnson 28 San Francisco Engineer
Michael Brown 42 Chicago Teacher
Emily Davis 31 Boston Scientist
複数の配置タイプを持つ動的なテーブル
異なるタイプのデータは、異なる配置スタイルで表示すると見栄えが良くなることが多いです。たとえば、テキストは左寄せ、数値は右寄せにすることが一般的です。混合配置を持つより洗練されたテーブルを作成しましょう。
/home/labex/project
ディレクトリに dynamic_table.py
という名前の新しいファイルを作成します。
## dynamic_table.py
print("Dynamic Table with Mixed Alignment")
print("-" * 50)
## Define some data
header = ["Product", "Price", "Quantity", "Total"]
products = [
["Laptop", 1299.99, 3, 3899.97],
["Mouse", 24.50, 10, 245.00],
["Monitor", 349.95, 2, 699.90],
["Keyboard", 49.99, 5, 249.95],
["Headphones", 89.95, 4, 359.80]
]
## Calculate column widths based on content
col_widths = [
max(len(str(header[0])), max(len(str(row[0])) for row in products)) + 2,
max(len(str(header[1])), max(len(f"${row[1]:.2f}") for row in products)) + 2,
max(len(str(header[2])), max(len(str(row[2])) for row in products)) + 2,
max(len(str(header[3])), max(len(f"${row[3]:.2f}") for row in products)) + 2
]
## Print header
print(f"{header[0]:<{col_widths[0]}}"
f"{header[1]:>{col_widths[1]}}"
f"{header[2]:>{col_widths[2]}}"
f"{header[3]:>{col_widths[3]}}")
print("-" * sum(col_widths))
## Print rows with appropriate alignment
for product in products:
print(f"{product[0]:<{col_widths[0]}}"
f"${product[1]:.2f}:>{col_widths[1] - 1}"
f"{product[2]:>{col_widths[2]}}"
f"${product[3]:.2f}:>{col_widths[3] - 1}")
## Print summary
total_quantity = sum(product[2] for product in products)
total_cost = sum(product[3] for product in products)
print("-" * sum(col_widths))
print(f"{'TOTAL':<{col_widths[0]}}"
f"{'':{col_widths[1]}}"
f"{total_quantity:>{col_widths[2]}}"
f"${total_cost:.2f}:>{col_widths[3] - 1}")
- このコードには修正が必要なエラーがあります。価格と合計の列の書式設定が正しくありません。修正しましょう。
## dynamic_table.py - corrected version
print("Dynamic Table with Mixed Alignment")
print("-" * 50)
## Define some data
header = ["Product", "Price", "Quantity", "Total"]
products = [
["Laptop", 1299.99, 3, 3899.97],
["Mouse", 24.50, 10, 245.00],
["Monitor", 349.95, 2, 699.90],
["Keyboard", 49.99, 5, 249.95],
["Headphones", 89.95, 4, 359.80]
]
## Calculate column widths based on content
col_widths = [
max(len(str(header[0])), max(len(str(row[0])) for row in products)) + 2,
max(len(str(header[1])), max(len(f"${row[1]:.2f}") for row in products)) + 2,
max(len(str(header[2])), max(len(str(row[2])) for row in products)) + 2,
max(len(str(header[3])), max(len(f"${row[3]:.2f}") for row in products)) + 2
]
## Print header
print(f"{header[0]:<{col_widths[0]}}"
f"{header[1]:>{col_widths[1]}}"
f"{header[2]:>{col_widths[2]}}"
f"{header[3]:>{col_widths[3]}}")
print("-" * sum(col_widths))
## Print rows with appropriate alignment
for product in products:
print(f"{product[0]:<{col_widths[0]}}"
f"${product[1]:.2f}".rjust(col_widths[1])
f"{product[2]}".rjust(col_widths[2])
f"${product[3]:.2f}".rjust(col_widths[3]))
## Print summary
total_quantity = sum(product[2] for product in products)
total_cost = sum(product[3] for product in products)
print("-" * sum(col_widths))
print(f"{'TOTAL':<{col_widths[0]}}"
f"".rjust(col_widths[1])
f"{total_quantity}".rjust(col_widths[2])
f"${total_cost:.2f}".rjust(col_widths[3]))
- 修正したファイルを保存して実行します。
python3 ~/project/dynamic_table.py
- この例を簡素化して、初心者にも分かりやすく、堅牢なものにしましょう。
## dynamic_table.py - simplified version
print("Dynamic Table with Mixed Alignment")
print("-" * 50)
## Define some data
header = ["Product", "Price ($)", "Quantity", "Total ($)"]
products = [
["Laptop", 1299.99, 3, 3899.97],
["Mouse", 24.50, 10, 245.00],
["Monitor", 349.95, 2, 699.90],
["Keyboard", 49.99, 5, 249.95],
["Headphones", 89.95, 4, 359.80]
]
## Fixed column widths
product_width = 15
price_width = 12
quantity_width = 10
total_width = 12
## Print header
print(f"{header[0]:<{product_width}}"
f"{header[1]:>{price_width}}"
f"{header[2]:>{quantity_width}}"
f"{header[3]:>{total_width}}")
print("-" * (product_width + price_width + quantity_width + total_width))
## Print rows with appropriate alignment
for product in products:
print(f"{product[0]:<{product_width}}"
f"{product[1]:>{price_width}.2f}"
f"{product[2]:>{quantity_width}}"
f"{product[3]:>{total_width}.2f}")
## Print summary
total_quantity = sum(product[2] for product in products)
total_cost = sum(product[3] for product in products)
print("-" * (product_width + price_width + quantity_width + total_width))
print(f"{'TOTAL':<{product_width}}"
f"{'':{price_width}}"
f"{total_quantity:>{quantity_width}}"
f"{total_cost:>{total_width}.2f}")
- この簡素化したバージョンで前のファイルを上書き保存して実行します。
python3 ~/project/dynamic_table.py
- 以下のように書式の整ったテーブルが表示されるはずです。
Dynamic Table with Mixed Alignment
--------------------------------------------------
Product Price ($) Quantity Total ($)
-------------------------------------------------------
Laptop 1299.99 3 3899.97
Mouse 24.50 10 245.00
Monitor 349.95 2 699.90
Keyboard 49.99 5 249.95
Headphones 89.95 4 359.80
-------------------------------------------------------
TOTAL 24 5454.62
財務レポートの作成
次に、より実用的な例として、配置技術を使って読みやすくした財務レポートを作成しましょう。
/home/labex/project
ディレクトリに financial_report.py
という名前の新しいファイルを作成します。
## financial_report.py
print("Monthly Financial Report")
print("=" * 60)
## Financial data
income_sources = [
["Salary", 5000.00],
["Freelance Work", 1200.50],
["Investments", 450.75],
["Other Income", 300.00]
]
expenses = [
["Rent", 1500.00],
["Utilities", 250.30],
["Groceries", 600.45],
["Transportation", 200.00],
["Insurance", 300.00],
["Entertainment", 150.25],
["Savings", 800.00],
["Miscellaneous", 300.00]
]
## Print Income Section
print("\nINCOME STATEMENT")
print("-" * 40)
print(f"{'Source':<20}{'Amount ($)':>20}")
print("-" * 40)
total_income = 0
for source, amount in income_sources:
total_income += amount
print(f"{source:<20}{amount:>20.2f}")
print("-" * 40)
print(f"{'Total Income':<20}{total_income:>20.2f}")
print()
## Print Expense Section
print("\nEXPENSE STATEMENT")
print("-" * 40)
print(f"{'Category':<20}{'Amount ($)':>20}")
print("-" * 40)
total_expenses = 0
for category, amount in expenses:
total_expenses += amount
print(f"{category:<20}{amount:>20.2f}")
print("-" * 40)
print(f"{'Total Expenses':<20}{total_expenses:>20.2f}")
print()
## Print Summary
print("\nMONTHLY SUMMARY")
print("-" * 40)
print(f"{'Total Income':<20}{total_income:>20.2f}")
print(f"{'Total Expenses':<20}{total_expenses:>20.2f}")
print("-" * 40)
balance = total_income - total_expenses
print(f"{'Net Balance':<20}{balance:>20.2f}")
## Add some conditional formatting for the balance
if balance > 0:
print(f"\nStatus: You saved ${balance:.2f} this month!")
else:
print(f"\nStatus: You overspent by ${-balance:.2f} this month.")
- ファイルを保存して実行します。
python3 ~/project/financial_report.py
- 列がきれいに配置された包括的な財務レポートが表示されるはずです。
Monthly Financial Report
============================================================
INCOME STATEMENT
----------------------------------------
Source Amount ($)
----------------------------------------
Salary 5000.00
Freelance Work 1200.50
Investments 450.75
Other Income 300.00
----------------------------------------
Total Income 6951.25
EXPENSE STATEMENT
----------------------------------------
Category Amount ($)
----------------------------------------
Rent 1500.00
Utilities 250.30
Groceries 600.45
Transportation 200.00
Insurance 300.00
Entertainment 150.25
Savings 800.00
Miscellaneous 300.00
----------------------------------------
Total Expenses 4101.00
MONTHLY SUMMARY
----------------------------------------
Total Income 6951.25
Total Expenses 4101.00
----------------------------------------
Net Balance 2850.25
Status: You saved $2850.25 this month!
この例は、適切な配置が複雑な財務情報を読みやすく理解しやすくすることができることを示しています。
要点
これらの例を通じて、以下のことを学びました。
- 一貫した配置でシンプルな固定幅テーブルを作成する
- データ型に基づいて異なる配置タイプを適用する(テキストは左寄せ、数値は右寄せ)
- 視覚的に整理された実用的なレポートを作成する
- 文字列書式設定方法を使って出力を精密に制御する
これらのスキルはコンソール出力だけでなく、レポートの生成、ログファイルの作成、またはテキストベースの形式でデータを提示する際にも応用できます。