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

如何用for循环以指定格式打印字典存储的购物清单信息?

解决商品列表格式化输出问题

你当前的问题是直接打印了字典对象,所以输出是字典的原生字符串结构,没法得到规整的对齐格式。要实现你想要的输出样式,需要提取每个商品的字段,用字符串格式化控制对齐和宽度,同时把商品名转成首字母大写的格式。

修改后的代码片段(重点是选项3的处理)

把你代码中elif user == 3:的部分替换成下面的代码:

elif user == 3:
    print("======================================")
    print("ITEM NAME               PRICE          QUANTITY")
    print("--------------------------------------")
    for item in grocery_list.values():
        # 将商品名转为首字母大写
        item_name = item['name'].capitalize()
        # 格式化输出:左对齐,固定宽度,价格保留两位小数
        print(f"{item_name:<20} {item['price']:<15.2f} {item['quan']:<10}")

代码说明

  • {item_name:<20}:商品名左对齐,占用20个字符宽度,确保不同长度的名称都能对齐后续内容
  • {item['price']:<15.2f}:价格左对齐,占用15个字符宽度,强制保留两位小数(不管输入是20.0还是200.00,都会统一显示为两位小数)
  • {item['quan']:<10}:数量左对齐,占用10个字符宽度

额外优化建议

把choice()函数移到while True循环外面,避免每次循环都重新定义函数,同时补充退出逻辑防止死循环,修改后的完整代码结构如下:

grocery_list = {}
print("   MY NEW AND IMPROVED GROCERY LIST")

def choice():  # 把函数移到循环外
    print("======================================")
    print("What would you like to do?"
          "\n1 - Add an Item" 
          "\n2 - Remove an Item"
          "\n3 - Print entire List"
          "\n4 - Calculate Cost"
          "\n5 - Exit program")
    user = int(input("\nChoice:"))

    if user == 1:
        print("======================================"
              "\nADD AN ITEM"
              "\n"
              "\nGive the following information:")
        name = str(input("Name:").lower())
        price = float(input("Price:"))
        quan = int(input("Quantity:"))
        grocery_list[name] = {"name": name, "price": price, "quan": quan}

    elif user == 2:
        print("======================================"
              "\nREMOVE AN ITEM"
              "\nWhat would you like to remove?")
        rmv = str(input("Item Name:").lower())

        if rmv in grocery_list:
            del grocery_list[rmv]

    elif user == 3:
        print("======================================")
        print("ITEM NAME               PRICE          QUANTITY")
        print("--------------------------------------")
        for item in grocery_list.values():
            item_name = item['name'].capitalize()
            print(f"{item_name:<20} {item['price']:<15.2f} {item['quan']:<10}")
    elif user ==5:
        print("Exiting program...")
        exit()  # 处理退出逻辑,终止循环

while True:
    choice()

这样修改后,当选择选项3时,就能输出你想要的规整格式了。

内容的提问来源于stack exchange,提问作者coffeegrinder

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 22:25:23