我正在为这个班写一个代码,却被卡住了。我的故障排除对我没有帮助。我遇到的第一个问题是,当将读取的文件拆分为列表中索引的[name,score]格式时,它会读取额外的行,但也会读取正确的行。然后在写入outfile时,它只读取列表中的最后一个索引,但是对于列表中的那个索引,这是正确的输出。我一直在读我的书,但找不到如何使用列表及其索引来遍历第二个if语句。任务如下: 编写一个程序,从名为“的外部文件中读取未知数量的保龄球手及其保龄球得分(可能值为1到300)bowlingscores.txt文件". 该文件将类似于以下内容:David 102 Hector 300 Mary 195 Jane 160 Sam 210将保龄球手的名字输出到一个名为bowlingaverages.txt文件". 在每个保龄球手的名字旁边,根据他们的分数打印一条消息:对于满分(等于300),对于高于平均分的分数输出“完美”,对于低于平均分的分数输出“高于平均值”,输出“低于平均值”您的程序必须至少包含一个函数(例如,计算平均值,确定要打印的适当消息等)。你知道吗
infile = open("bowlingscores.txt", "r")
name=0
score=0
averagescore=0
count=0
bowlersinfo=[]
for line in infile:
if line.strip().isdigit():
score=int(line)
else:
name=line.strip()
bowler= name, score
bowlersinfo.append(bowler)
print bowlersinfo
averagescore += score
infile.close()
averagescore /= float(len(name))
for count in range (len(name)):
if score==300:
outcome= "Perfect"
elif score > averagescore:
outcome= "Above Average"
elif score== averagescore:
outcome= "Average"
else:
outcome= "Below Average"
outfile = open("bowlingaverages.txt", "w")
outfile.write(name, )
outfile.write(outcome)
outfile.close()
print ("%s, %0.0f, %s" % (name, float(score), outcome))
这是我得到的结果。粗体字是我需要的输出。不是所有的额外费用。每个名字都应该像最后一行一样显示。
[('David',0),('David',102),('Hector',102),('Hector',300),('Mary',300),('Mary',195),('Jane',195),('Jane',160),('Sam',160),('Sam',210)]
Sam,210岁,高于平均水平
不确定循环结构是否正确,以及读取文件时是否正确读取字符串。你知道吗
我不想把你原来的代码弄乱太多。所以我改变了一些东西。你可以让你的代码更紧凑。你知道吗
相关问题 更多 >
编程相关推荐