在将答案输出到文本文件时遇到问题



我似乎无法将我需要的东西输出到这个文本文件中。基本上,我必须从文本文件中获取投球手及其分数,并输出他们的名字,他们的分数,如果它是"完美"高于平均水平"或"低于平均水平",这是我到目前为止的代码。

bowler_scores = {}
infile = open('bowlingscores.txt', 'r')
for line in infile:
    if line.strip().isalpha():
        names = line.strip()
    elif line.strip().isdigit():
        scores = int(line)
        bowler_scores[names] = scores
total = sum(bowler_scores.values())
num_scores = len(bowler_scores.values())
def my_avg(x, y):
    average = float(x/y)
    return average
my_avg(total, num_scores)
infile.close()
outfile = open('output.txt', 'w')
for x, y in bowler_scores.items():
    a = str(x)
    b = str(y)
    if y == 300:
        outfile.write('{} {} Perfect/n'.format(a, b))
    elif y > my_avg(total, num_scores):
        outfile.write('{} {} Above average'.format(a, b))
    elif y < my_avg(total, num_scores):
        outfile.write('{} {} Below average'.format(a, b))

我不知道如何将答案打印到另一个文本文件中。我见过有人问同样的问题,但在给出的答案中,他们只是打印它而不是将其输出到文本文件中。请帮忙?

bowler_scores = {}
for line in open('bowlingscores.txt', 'rb'):
    line = line.strip()
    if line.isalpha():
        name = line.strip()
        bowler_scores[name] = [] #1
    elif line.isdigit():
        score = int(line)
        bowler_scores[name].append(score) #2
def avg(x, y):
    return x/float(y) 
total = sum([sum(scores) for scores in bowler_scores.values()]) #3
num_scores = sum(len(value) for value in bowler_scores.values()) #4
total_avg = avg(total, num_scores) # 5
output = open('output.txt','wb')
for name, scores in bowler_scores.items(): #6
    bowler_avg = avg(sum(scores),len(scores)) #7
    if sum(scores) == 60: 
        output.write('{0} {1} Perfectrn'.format(name, scores))
    elif bowler_avg > total_avg: #8
        output.write('{} {} Above averagern'.format(name, scores)) #9
    elif bowler_avg < total_avg:
        output.write('{} {} Below averagern'.format(name, scores))
output.close()

您的代码有一些小问题:

  1. 您首先必须在字典中创建投球手,并带有空列表您将把分数放在哪里
  2. 然后将分数附加到此列表
  3. 为了计算我使用列表压缩的总和,我对每个投球手的分数求和,然后对它们的总和求和。
  4. 还使用列表压缩来计算分数的大小
  5. 您可以在变量中分配 avg 以再次重用它
  6. 使用更具描述性的名称
  7. 计算投球手的平均得分
  8. 检查平均值是
  9. 大于还是小于平均值
  10. 你可以直接使用项目,它们将被转换为字符串,不需要使用 str()

如果每个玩家只有一个分数,下面是代码:

for line in open('bowlingscores.txt', 'rb'):
    line = line.strip()
    if line.isalpha():
        name = line.strip()
    elif line.isdigit():
        score = int(line)
        bowler_scores[name] = score
...
total = sum(bowler_scores.values())
num_scores = len(bowler_scores.values())
...
output = open('output.txt','wb')
for name, score in bowler_scores.items():
    if score == 300:
       output.write('{0} {1} Perfectrn'.format(name, score))
    elif score > total_avg:  #8
        output.write('{} {} Above averagern'.format(name, score))
    elif score < total_avg:
        output.write('{} {} Below averagern'.format(name, score))
output.close()

最新更新