关于简单python脚本的问题

时间:2018-02-16 15:03:15

标签: python list dictionary

我有一个家庭作业,写一个简单的购物清单,脚本应该能够:

  1. 接受用户输入的变量,例如item_name,数量和项目成本

  2. 使用从用户收集的信息,创建一个字典条目并将其添加到名为grocery_history的列表

  3. 打印出以下列格式输入的所有项目:变量→数字名称价格item_total

  4. 最后输出所有项目的总成本

  5. 这是我的代码:

    grocery_item = {}
    grocery_history=[{}]
    stop = 'go'
    item_name = input("Item name:")
    quantity = input("Quantity purchased:")
    cost = input("Price per item:") 
    grocery_history.append(item_name)
    grocery_history.append(quantity)
    grocery_history.append(cost)
    
    cont = input("Would you like to enter another item?\nType 'c' for continue or 'q' to quit:")
    while cont != 'q':
      item_name = input("Item name:")
      quantity = input("Quantity purchased:")
      cost = input("Price per item:") 
      cont = input("Would you like to enter another item?\nType 'c' for continue or 'q' to quit:")
    
    
      grocery_history.append(item_name)
      grocery_history.append(quantity)
      grocery_history.append(cost)
    
    
    
    grand_total = []
    
    number = grocery_history[quantity]
    price = grocery_history[cost]
    
    for grocery_history in grocery_item:    
      item_total = int(number)*float(price)
      grand_total.append(item_total)
       print(grocery_history[number][name] + "@" [price]:.2f + "ea'.format(**grocery_item)")     
    
    
    item_total = 0
    
    
    print ("Grand total:" + str(grand_total))
    

    在我的number = grocery_history[quantity]     price = grocery_history [cost] statement I get a Key Error 2`,我不知道为什么,密钥应该存在,但也许它们没有被正确地添加到列表中。 任何帮助将不胜感激,如果您需要更多详细信息,请告诉我,我将在其中进行编辑。

2 个答案:

答案 0 :(得分:0)

这是一个工作示例(以下说明):

grocery_history={'item_name':[], 'quantity':[], 'cost':[]}
cont = 'c'
while cont != 'q':
    item_name = input("Item name:")
    quantity = int(input("Quantity purchased:"))
    cost = int(input("Price per item:"))
    cont = input("Would you like to enter another item?\nType 'c' for continue or 'q' to quit:")

    grocery_history['item_name'].append(item_name)
    grocery_history['quantity'].append(quantity)
    grocery_history['cost'].append(cost)


grand_total = 0
for i in range(len(grocery_history['item_name'])):
    item_name = grocery_history['item_name'][i]
    quantity = grocery_history['quantity'][i]
    cost = grocery_history['cost'][i]

    priceTimesQuantity = quantity * cost
    grand_total = grand_total + priceTimesQuantity
    message = 'Bought {} x{} (each: {}$) to a total of: {}'.format(item_name, quantity, cost, priceTimesQuantity)
    print( message )

finalmessage = 'Grand Total: {}'.format(grand_total)
print(finalmessage)
  1. 我减少了第一个循环上方的部分(想一想)
  2. grocery_history现在是包含3个列表的字典。例如:
    enter image description here
  3. 我们现在使用项目(append
  4. 向下填写这些列表
  5. 当用户完成时,我们再次使用i作为索引列表(请参阅图像左侧的小灰色数字) 然后,对于每个项目,我们从列表中加载详细信息并计算总价格 此外,我们将总数添加到grand_total,这是一个数字(从零开始)与第二个循环相加。
  6. 在第二个循环完成后,我们打印最终值(总和)
  7. 文本中的

    "some text {}".format(var) - {}是字符串后面的var的占位符

答案 1 :(得分:0)

您的grocery_history是一个词典列表。在grocery_history中创建条目时,只需将简单值添加到列表中,而不是字典。

如果您知道每个元素的确切大小,解析列表应该不是问题,但更优雅的解决方案是在列表中创建正确描述杂货的另一个对象。

grocery_item = {}
grocery_history=[{}]
stop = 'go'
item_name = input("Item name:")
quantity = input("Quantity purchased:")
cost = input("Price per item:")
# We define each grocery as a dictionary containing the key "item_name" and values formed by another dict
# that is made up of keys "quantity" and "cost" with their respective values
# Each grocery will look like this {'grocery_name': {'quantity': 2.5, 'cost': 21.44}}
groceries = {item_name: {'quantity': float(quantity), 'cost': float(cost)}}
grocery_history.append(groceries)

cont = input("Would you like to enter another item?\nType 'c' for continue or 'q' to quit:")
while cont != 'q':
  item_name = input("Item name:")
  quantity = input("Quantity purchased:")
  cost = input("Price per item:")
  cont = input("Would you like to enter another item?\nType 'c' for continue or 'q' to quit:")
  groceries = {item_name: {'quantity': float(quantity), 'cost': float(cost)}}
  grocery_history.append(groceries)

total = 0
for grocery in grocery_history:
  for name, properties in grocery.items():
    total+= properties['quantity']*properties['cost']

print('Total of groceries is: ', total)