Python公交订票系统如何按指定格式打印客户订单历史
问题原因
- 你第一次尝试直接打印两个列表对象,输出自然会带上列表的
[]括号符号,没有拆分每一条订单单独打印 - 第二次尝试写
customer_history[0]是取输入姓名字符串的第一个字符,比如输入Emily时取到的是E,你的两个字典的key都是完整姓名,自然会触发KeyError报错
解决代码
customers_tickets = {'Milla':[1], 'Theruni':[1], 'Anna':[4], 'Emily':[4,2]} customers_destinations = {'Milla':['Sydney'], 'Theruni':['Perth'], 'Anna':['Perth'], 'Emily':['Perth','Darwin']} print("Please enter the customer name to check order history:\n") customer_history = input() # 先校验客户是否存在,避免报错 if customer_history not in customers_tickets: print(f"未找到客户{customer_history}的订单记录") else: # 打印表头 print(f"{'Destinations':<30} {'Number of Tickets'}") # 配对遍历目的地和对应票数 for dest, ticket_num in zip(customers_destinations[customer_history], customers_tickets[customer_history]): # 格式化对齐输出 print(f"{dest:<30} {ticket_num:>18}")
代码说明
- 用
zip()函数可以把同一个客户的目的地列表和票数列表按索引一一配对,每次循环取出一条订单的目的地和对应票数 - 格式化字符串里的
<30表示内容左对齐、总宽度占30个字符,>18表示内容右对齐、总宽度占18个字符,刚好匹配你需要的对齐效果 - 增加了客户存在性校验,避免输入不存在的姓名时触发
KeyError
内容的提问来源于stack exchange,提问作者zedkpea
相关产品推荐
相关产品推荐

