【问题标题】:Looping through a dictionary (grocery lists)遍历字典(杂货清单)
【发布时间】: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


【解决方案1】:

您在i 上有一个for 循环,但实际上您并没有在循环中的任何地方使用i。所有grocery_history[0] 应该是i。您还应该给它一个更具描述性的名称,例如item。而且您不需要将item_total 重置为零。

for item in grocery_history:
  item_total = item['number']*item['price']
  print(item['number'], 
        item['name'], ' @', '$',
        item['price'], ' ea', '$', 
        item_total)
  grand_total += item_total

【讨论】:

  • 感谢您的帮助。老实说,我不知道我必须在 for 循环中使用变量 I。但这确实有道理。
  • @AustinHoward 在某些情况下迭代器没有在 for 循环中使用,但如果您的代码只涉及不变的内容,那么您将获得相同的输出时间。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-17
  • 1970-01-01
  • 2019-09-24
相关资源
最近更新 更多