兩個文件:`employee.txt`(工號 姓名),`bonus.txt`(工號 獎金)。合併輸出:工號 姓名 獎金,按姓名首字母排序。
employee.txt: 100 Jason Smith 200 John Doe 300 Sanjay Gupta 400 Ashok Sharma bonus.txt: 100 $5,000 200 $500 300 $3,000 400 $1,250
# coding=utf-8
with open("bonus.txt") as f1:
bonus = {line.split()[0]: line.split()[1] for line in f1}
with open("employee.txt") as f2:
emps = [line.split() for line in f2] # [id, first, last]
# 按姓名首字母排序(這裡以 first name 為例)
emps.sort(key=lambda x: x[1])
for e in emps:
emp_id = e[0]
if emp_id in bonus:
print(f"{emp_id} {e[1]} {e[2]} {bonus[emp_id]}")
100 Jason Smith $5,000 200 John Doe $500 300 Sanjay Gupta $3,000 400 Ashok Sharma $1,250
題目原意可能是 Shell 腳本(`join` + `sort`),但 Python 更易讀、跨平台、易維護。
Python 處理文本合併極其簡潔:讀取→字典映射→列表排序→格式化輸出。幾行代碼解決實際數據處理需求。