我正在尝试创建一个包含字典列表的简单程序。杂货历史是字典列表,字典是杂货项目。这是代码:
'''
The task is broken down into three sections.
Section 1 - User Input
Section 2 - loop through the grocery list
Section 3 - provide output to the console
'''
grocery_item = {}
grocery_history = []
stop = 'go'
while stop != 'q':
item_name = input("Item name:\n")
quantity = int(input("Quantity purchased:\n"))
cost = float(input("Price per item:\n"))
grocery_item['name'] = item_name
grocery_item['number'] = quantity
grocery_item['price'] = cost
grocery_history.append(grocery_item)
stop = input("Would you like to enter another item?\nType 'c' for continue or 'q' to quit:\n")
print(grocery_history)
grand_total = 0
for grocery_item in range(0, len(grocery_history)):
item_total = grocery_history[grocery_item]['number'] * grocery_history[grocery_item]['price']
grand_total += item_total
print(str(grocery_history[grocery_item]['number']) + " " + grocery_history[grocery_item]['name'] + " @ $%.2f" % grocery_history[grocery_item]['price'] + " ea \t$%.2f" % item_total)
item_total = 0.0
print("Grand total: $%.2f" % grand_total)
print(grocery_history)
如果您想知道,这个赋值的提示告诉我在我的 for 循环中使用变量grocery_item。我通常会选择一个不同的名字,因为它变得令人困惑。我还添加了一些打印语句来打印出grocery_history 的内容以查看出了什么问题,并且我确认它是在将字典添加到grocery_history 列表时,因为某种原因它会更新现有的字典项以匹配新的一个正在添加。我无法弄清楚我做错了什么。任何帮助将不胜感激!