You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 07:42:01