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

Python 3购物清单Codio挑战:如何将商品以字典形式添加至列表

嘿,别担心,刚学编程几周有疑问太正常啦!我来帮你搞定这个把商品字典添加到列表的问题~

你现在遇到的核心问题是:复用了同一个字典对象。你原来的代码里current_item是在循环外面创建的,每次循环修改它的内容时,列表里之前添加的条目其实都是指向这个字典的“引用”——就像大家都指着同一个盒子,你改盒子里的东西,所有人看到的都会变,最后列表里所有元素都会变成最后一次输入的商品信息。

给你两种简单的解决办法,推荐第一种,更适合新手理解:

方法1:每次循环创建新字典

把创建字典的代码放到循环里面,这样每次添加的都是全新的独立字典,不会互相影响:

grocery_history = []
stop = True

while stop:
    # 每次循环都生成一个新的空字典
    current_item = {}
    current_item['name'] = input('Item name: ')
    current_item['quantity'] = int(input('Amount purchased: '))
    current_item['cost'] = float(input('Cost per item: '))
    
    # 将这个新字典加入购物历史列表
    grocery_history.append(current_item)
    
    # 加个选项让你决定是否继续添加
    choice = input('要不要再添加一个商品?(y/n): ')
    if choice.lower() == 'n':
        stop = False

# 打印看看结果
print("\n你的购物清单历史:")
for item in grocery_history:
    print(f"商品名:{item['name']},数量:{item['quantity']},单价:${item['cost']:.2f}")

方法2:添加字典的副本(适合想复用初始字典的情况)

如果一定要在循环外定义current_item,那每次添加到列表时,要给字典做个“副本”,这样列表里存的是独立的拷贝:

grocery_history = []
current_item = {}
stop = True

while stop:
    current_item['name'] = input('Item name: ')
    current_item['quantity'] = int(input('Amount purchased: '))
    current_item['cost'] = float(input('Cost per item: '))
    
    # 添加字典的副本,而不是原字典本身
    grocery_history.append(current_item.copy())
    
    choice = input('要不要再添加一个商品?(y/n): ')
    if choice.lower() == 'n':
        stop = False

另外给你两个小提示:

  • input()本身返回的就是字符串,所以str(input(...))可以直接写成input(...),没必要多一层转换;
  • 商品价格用float类型存储会更合理,后续如果要计算总价之类的操作会更方便。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:16:51