从文本文件的Python保龄球程序字典

时间:2014-12-02 05:20:26

标签: python file

以下是我的任务。我被困在如何在字典中包含总数。我甚至不确定这是否可行,但我需要它来做平均值。我希望能朝着正确的方向前进。 :)

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

David
102
Hector
300
Mary
195
Jane
160
Sam
210

将保龄球的名字输出到名为" bowlingaverages.txt"的外部数据文件中。在每个投球手的名字旁边,根据他们的分数打印一条消息: 对于完美分数(等于300),输出“完美” 对于那些高于平均分数的分数,输出“高于平均水平” 对于低于平均水平的人,输出“低于平均水平”

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

3 个答案:

答案 0 :(得分:0)


是不是可以简单地将total添加为字典中的键并在循环中更新它?

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

答案 1 :(得分: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

答案 2 :(得分: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