2011-11-07 48 views
1

这是我正在做的功课。总字典

我有一个看起来像这样的.txt文件。

11 
eggs 
1.17 
milk 
3.54 
bread 
1.50 
coffee 
3.57 
sugar 
1.07 
flour 
1.37 
apple 
.33 
cheese 
4.43 
orange 
.37 
bananas 
.53 
potato 
.19 

我试图做的是保持运行总计,当您在Word类型“鸡蛋”,那么单词“面包”,它需要同时添加的成本,并继续下去,直到“EXIT”我也会遇到一个'KeyError'并需要帮助。

def main(): 
    key = '' 
    infile = open('shoppinglist.txt', 'r') 
    total = 0 
    count = infile.readline() 
    grocery = '' 
    groceries = {} 


    print('This program keeps a running total of your shopping list.') 
    print('Use \'EXIT\' to exit.') 


    while grocery != 'EXIT': 

     grocery = input('Enter an item: ') 

     for line in infile: 
      line = line.strip() 
      if key == '': 
       key = line 

      else: 
       groceries[key] = line 
       key = '' 

     print ('Your current total is $'+ groceries[grocery]) 

main() 

回答

1

该文件是否包含每种不同杂货的价格?

用户input声明最后应该有一个.strip(),因为有时可以从用户输入中包含行尾字符。

您应该只需要读取一次文件,而不是循环中。

当用户进入一个杂货店项目它应该像你说的检查它是否存在:

if grocery in groceries: 
    ... 
else: 
    #grocery name not recognised 

我认为你必须要一个单独的字典来存储的每一个杂货店像这样计数:http://docs.python.org/library/collections.html#collections.Counter

import collections 
quantitiesWanted = collections.Counter() 

然后任何杂货店可以被要求这样quantitiesWanted['eggs']这将默认返回0。做类似quantitiesWanted['eggs'] += 1的东西会将其增加到1等等。

为了获得当前总,你可以这样做:

total = 0 
for key, value in quantitiesWanted: 
    total += groceries[key] * value