【问题标题】:Questions about simple python script关于简单python脚本的问题
【发布时间】:2018-07-27 12:33:47
【问题描述】:

我有一个家庭作业,要写一个简单的购物清单,这个脚本应该可以:

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

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

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

  4. 最后输出所有物品的总成本

这是我的代码:

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] 价格 = 杂货历史[成本]statement I get aKey Error 2`,我不知道为什么,密钥应该存在,但也许它们没有被正确添加到列表中。 任何帮助将不胜感激,如果您需要更多详细信息,请告诉我,我会编辑它们。

【问题讨论】:

  • 看来grocery_history是一个列表,而不是字典。
  • 您正在尝试使用键 (str) 访问列表。它不能工作。

标签: python list dictionary


【解决方案1】:

这是一个工作示例(解释如下):

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 个列表的字典。例如:
  3. 我们现在用项目 (append) 向下填充这些列表
  4. 当用户完成后,我们再次进入以i为索引的列表
    (参见图像左侧的小灰色数字) 然后,对于每个项目,我们从列表中加载详细信息并计算总价格 此外,我们将总数添加到 grand_total,这是一个与第二个循环相加的数字(从零开始)。
  5. 在第二个循环完成后,我们打印最终值(总和)

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

【讨论】:

    【解决方案2】:

    您的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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-02
      • 1970-01-01
      • 2016-05-10
      • 1970-01-01
      • 2011-09-21
      • 1970-01-01
      相关资源
      最近更新 更多