2011-11-07 46 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