我似乎无法输出我需要的文本文件。基本上我必须从文本文件和他们的分数中选择保龄球,并输出他们的名字,他们的分数,如果它是“完美”“高于平均水平”或“低于平均水平”这是我的代码到目前为止。
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))
我无法弄清楚如何将答案打印到另一个文本文件中。我见过有人询问同样的问题,但在答案中他们只是打印出来而不是将其输出到文本文件中。请帮忙吗?
答案 0 :(得分:1)
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} Perfect\r\n'.format(name, scores))
elif bowler_avg > total_avg: #8
output.write('{} {} Above average\r\n'.format(name, scores)) #9
elif bowler_avg < total_avg:
output.write('{} {} Below average\r\n'.format(name, scores))
output.close()
您的代码存在一些小问题:
如果每个玩家只有一个分数,那么代码就是:
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} Perfect\r\n'.format(name, score))
elif score > total_avg: #8
output.write('{} {} Above average\r\n'.format(name, score))
elif score < total_avg:
output.write('{} {} Below average\r\n'.format(name, score))
output.close()