【发布时间】:2019-10-02 21:23:30
【问题描述】:
在我的脚本类介绍中,这个想法是创建一个基本的购物清单,以(项目、数量、价格)的形式从用户那里获取输入。您将这些存储在字典中,然后询问用户是否要向列表中添加更多项目或退出。如果他们向列表中添加更多内容,则脚本希望您将其添加到嵌套字典条目的“列表”中。当用户退出程序时,它应该打印出这种性质的东西。
2 milk at $2.99 ea for a total of: x
1 eggs at 1.99 ea for a total of: x
Grand total: x
我的问题是:我可以用这种方式打印出来,但它只会一遍又一遍地打印出同一行。我检查过它确实将条目添加到grocery_history 列表中。它们在那里,但是当我循环打印它们时,它只会为列表中的每个项目打印出第一个条目。
i.e.
2 milk at $2.99 ea for a total of: x
2 milk at $2.99 ea for a total of: x
grand total: x
我不太擅长使用列表或字典。它们是我在编码中苦苦挣扎的一件事。
我尝试增加列表的索引值,结果报错。
#Task: Create the empty data structure
grocery_item = {}
grocery_history = []
#Variable used to check if the while loop condition is met
stop = 'go'
choice = ''
while choice != 'q':
item_name = input('Item name: ')
quantity = int(input('Quantity purhcased: '))
cost = float(input('Price per item: '))
GL={'name':item_name, 'number': int(quantity), 'price':float(cost)}
grocery_item.update(GL)
print(GL)
grocery_history.append(GL)
choice = input("Would you like to enter another item?\nType 'c' for continue or 'q' to quit:\n")
if choice == 'q':
#print(grocery_history)
break
elif choice =='c':
continue
print(grocery_history)
grand_total = 0
#Define a 'for' loop.
total = 0
rows = len(grocery_history)
for i in grocery_history:
#Calculate the total cost for the grocery_item.
item_total = grocery_history[0]['number']*grocery_history[0]['price']
#Output the information for the grocery item to match this example:
print(grocery_history[0]['number'], grocery_history[0]['name'], ' @', '$',grocery_history[0]['price'], ' ea', '$', item_total)
#Add the item_total to the grand_total
grand_total += item_total
item_total = 0
#Print the grand total
print(grand_total)
【问题讨论】:
-
grocery_history似乎是一个字典列表。当你迭代它时,i将是一个字典。在您的循环中,您总是查看grocery_history中的第一项。尝试改用i。 -
感谢@afro,我不敢相信它这么简单。嗯,其实我可以。因为再一次,我很讨厌字典和列表。
标签: python list loops dictionary