2014-12-02 100 views
0

以下是我的任务。我被困在如何在字典中包含总数。我甚至不确定这是否可能,但我需要它来做平均。我希望推动正确的方向。 :)来自文本文件的Python保龄球程序字典

作业:编写一个程序,可以从名为“bowlingscores.txt”的外部文件中读取未知数量的保龄球及其保龄球分数(可能值为1至300)。该文件将类似于以下内容:

David 
102 
Hector 
300 
Mary 
195 
Jane 
160 
Sam 
210 

输出的保龄球的名字名为‘bowlingaverages.txt’外部数据文件。输入“perfect” 对于那些高于平均分数的分数,输出“高于平均水平” 对于低于平均水平的输出,输出“低于平均水平”

scores = {} 
total = 0 


def bowl_info(filename): 
    infile = open("bowlingscores.txt", "r") 

    for line in infile:  
     if line.strip().isdigit(): 
      score = int(line) 
      scores[name] = score 
      total += score  
     else: 
      name = line.strip() 
    return scores 




bowl_info("bowlingscores.txt") 
numbowlers = len(scores) 
total = 0 
average = total/numbowlers 

回答

0

难道不能够简单地对总添加在词典中的关键,在循环更新它,你都做了些什么?

scores = {'total': 0} 


def bowl_info(filename): 
    infile = open("bowlingscores.txt", "r") 

    for line in infile:  
     if line.strip().isdigit(): 
      score = int(line) 
      scores[name] = score 
      scores['total'] += score  
     else: 
      name = line.strip() 
    return scores 




bowl_info("bowlingscores.txt") 
numbowlers = len(scores) 
#total = 0 REMOVE THIS LINE 
average = scores['total']/numbowlers 
+0

我尝试过,但得到了KeyError:'total'。 :( – Holly 2014-12-02 06:10:50

0

返回score以及total

def bowl_info(filename): 
    total = 0 # you have to define toatl within function. 
    .. 
    .. 
    return scores, total 

赶上通过函数调用这两个对象,并在代码中使用它: -

scores, total = bowl_info("bowlingscores.txt") 

#score = {'Jane': 160, 'Hector': 300, 'Mary': 195, 'Sam': 210, 'David': 102} 
#total = 967 
+0

我知道你做了什么,但是当我调用函数并试图获得平均值时,总没有定义,我不知道我在做什么错误,我会睡在它上面:)谢谢!!!! – Holly 2014-12-02 07:21:39

+0

@霍利定义总功能,我更新了代码检查它。 – 2014-12-02 07:34:15

+0

@Holly检查更新的代码。 – 2014-12-02 07:47:07

0

检查和分析,我涵盖了所有的你想要:

>>> my_dict ={} 
>>> f = open('bowlingscores.txt') 
>>> for x in f: 
...  my_dict[x.strip()] = int(f.next()) # f.next() moves the file pointer to nextline and return is value 
... 
>>> my_dict 
{'Jane': 160, 'Hector': 300, 'Mary': 195, 'Sam': 210, 'David': 102} 
>>> total_score = sum(my_dict.values()) 
>>> total_score 
967 
>>>avg = float(total_score/len(my_dict.values())) 
193.0 
>>> for x,y in my_dict.items(): 
...  if y == 300: 
...   print x,y,"Perfect" 
...  elif y >=avg: 
...   print x,y,"Above Average" 
...  elif y <= avg: 
...   print x,y,"Below Average" 
... 
Jane 160 Below Average 
Hector 300 Perfect 
Mary 195 Above Average 
Sam 210 Above Average 
David 102 Below Average