Python 如何在while循环中附加列表而不覆盖以前的结果

Python 如何在while循环中附加列表而不覆盖以前的结果,python,Python,我正在为Python课程的购物清单编写脚本。一切看起来都很好,除了每次在列表中添加新的字典条目时,都会覆盖旧的值。我在这里已经发现了很多类似的问题,但我不愿意承认我还不太理解很多答案。如果我自己问这个问题并了解上下文,希望我能更好地理解它。这是我的密码: grocery_item = {} grocery_history = [] stop = 'c' while stop == 'c': item_name = input('Item name:\n') quantity =

我正在为Python课程的购物清单编写脚本。一切看起来都很好,除了每次在列表中添加新的字典条目时,都会覆盖旧的值。我在这里已经发现了很多类似的问题,但我不愿意承认我还不太理解很多答案。如果我自己问这个问题并了解上下文,希望我能更好地理解它。这是我的密码:

grocery_item = {}
grocery_history = []
stop = 'c'
while stop == 'c':
  item_name = input('Item name:\n')    
  quantity = input('Quantity purchased:\n')  
  cost = input('Price per item:\n')
  grocery_item = {'name':item_name, 'number': int(quantity), 'price': 
  float(cost)}
  grocery_history.append(grocery_item)   <<< # OVERWRITES OLD VALUES.
  stop = input("Would you like to enter another item?\nType 'c' for 
  continue 
  or 'q' to quit:\n")
grand_total = 0
for items in range(0,len(grocery_history)): 
  item_total = grocery_item['number'] * grocery_item['price']
  grand_total = grand_total + item_total
  print(str(grocery_item['number']) + ' ' + str(grocery_item['name']) + ' 
  ' + '@' + ' ' + '$' + str(grocery_item['price']) + ' ' + 'ea' + ' ' + 
  '$' + 
  str(item_total))
  item_total == 0
print('Grand total:$' + str(grand_total))
杂货店_项目={}
杂货店历史=[]
停止='c'
当stop=='c'时:
项目名称=输入('项目名称:\n')
数量=输入('购买的数量:\n')
成本=输入('每项价格:\n')
杂货店商品={'name':商品名称,'number':整数(数量),'price':
浮动(成本)}

杂货店历史记录。附加(杂货店项目)您创建
dict
多个对象,并将每个对象分配给
杂货店项目
。每个都将替换该名称下的最后一个,这很好,因为您还将
附加到
杂货店历史记录中。但是,您从不使用
列表的(除了确定要执行的总计循环的迭代次数);相反,您可以再次使用
screery\u item
,它仍然具有您上次分配给它的任何单个值

替换

for items in range(0,len(grocery_history)):


(你从来没有使用过

问题不在于你认为它在哪里。正在将这些值正确附加到历史记录中。您可以使用
打印(杂货店历史记录)
检查您自己

问题出在
for
循环中。您正在从
杂货店项目
(即用户输入的最后一个项目)而不是从整个
杂货店历史
列表中读取。将
for
循环替换为以下循环:

for i in range(0,len(grocery_history)):
  item_total = grocery_history[i]['number'] * grocery_history[i]['price']
  grand_total = grand_total + item_total
  print(str(grocery_history[i]['number']) + ' ' + str(grocery_history[i]['number']) + ' ' + '@' + ' ' + '$' + str(grocery_history[i]['number']) + ' ' + 'ea' + ' ' + '$' + str(item_total))
  item_total == 0
print('Grand total:$' + str(grand_total))

@DavisHerring只是想说明for循环应该读取
杂货店历史记录中的每个元素。确实很难看。
for i in range(0,len(grocery_history)):
  item_total = grocery_history[i]['number'] * grocery_history[i]['price']
  grand_total = grand_total + item_total
  print(str(grocery_history[i]['number']) + ' ' + str(grocery_history[i]['number']) + ' ' + '@' + ' ' + '$' + str(grocery_history[i]['number']) + ' ' + 'ea' + ' ' + '$' + str(item_total))
  item_total == 0
print('Grand total:$' + str(grand_total))