问题:
这是scores.txt,其中包含5个数字的列表。文件中的数字是垂直列表,如下所示:
86
92
77
83
96
我现在有以下代码,但不断收到错误:
第19行,在 main()的 第17行,主要是 showscores(得分)第2行,在showcores中 sum_scores = sum(得分)
TypeError:+:'int'和'str'
的不支持的操作数类型def showscores(scores):
sum_scores = sum(scores)
average = float(sum_scores // len(scores))
print ("The scores are: " + str(scores))
print ("Average score: " + str(average))
def main():
scores = []
scores_file = open("scores.txt", 'r')
line_list = list(scores_file.readlines())
i = 0
while i < len(line_list):
scores.append(line_list[i])
i += 1
scores_file.close()
showscores(scores)
main()
答案 0 :(得分:2)
这里没有人真正帮助他。很明显OP刚刚开始学习编程,并且正在解决一些问题。 (右?)
给他所有解决方案只是为了得到一些代表不会做。
我认为OP面临着练习或家庭作业,并确定了要遵循的步骤。
OP,起初很难,但一切都会好的。
描述似乎会给您带来更多麻烦的部分:
while
希望您逐行阅读文本文件(这就是为什么需要while
循环,为每一行重复相同的操作)。对于每一行,将其内容添加到您先前创建的列表中。showscores
(您还需要编写代码),如果我理解您收到的指示,您就可以处理&#34;那里的数据。因为你当前的名单中有什么?每行一串。处理它,以便将其变为更实用的实际数字。有关代码示例,请查看其他答案。即使他们可能会麻烦你,因为他们,恕我直言,似乎并没有“友善友好”#34;如果您遇到任何问题,请不要忘记使用最喜欢的搜索引擎,阅读文档等。
编辑:因为您似乎特别挣扎着while
循环。这是一个展示它的小代码。
之前请查看该小教程以了解其背后的基本知识:http://www.afterhoursprogramming.com/tutorial/Python/While-Loop/
因此,除了为您完成所有操作的魔术for
循环之外,您可以使用while
执行此操作:
def main():
scores = []
scores_file = open("path to scores.txt", 'r')
line_list = list(scores_files.readlines())
i = 0
while i < len(line_list):
scores.append(line_list[i])
i += 1
showscores(scores)
答案 1 :(得分:0)
我试过这个并且有效:
def showscores(scores):
sum_scores = sum(scores)
average = float(sum_scores // len(scores))
print ("The scores are: " + str(scores))
print ("Average score: " + str(average))
def main():
f = open("PATH TO YOUR FILE", 'r')
content = list(f.readlines())
scores = []
for x in content:
scores.append(int(x.replace(" ", "")))
showscores(scores)
main()
希望这适合你
答案 2 :(得分:0)
这是一项非常简单的任务......
def showscores(scores):
# calculate average with two decimal place
print '%.2f' % (float(sum(scores)) / len(scores))
if __name__ == '__main__':
scores = []
f_obj = open('scores.txt') # open scores.txt
for line in f_obj.readlines(): # read line by line
if line.strip() == '': # skip empty line
continue
else: # add score to scores list
scores.append(int(scores))
f_obj.close() # close file.
showscores(scores) # call showscores function
答案 3 :(得分:0)
使用异常处理的解决方案。
<强>代码强>:
import os
def showscores(scores):
""" average """
#- Get Total sum from the scroes list by sum in-build function.
total = sum(scores)
print "Debug 4:", total
#- Get average and handle dividing by zero exception.
try:
avg = total/float(len(scores))
except ZeroDivisionError:
avg = 0.0
#- Print result.
print "average of scores is= %.2f"%avg
return
def main():
""" Get Scores from the file."""
file_name = "scores.txt"
#- Check file is exists or not.
if not os.path.isfile(file_name):
print "Input file is not found."
return []
scores = []
#- Read file content.
with open(file_name, "rb") as fp:
#- Iterate file upto EOF line
while True:
line = fp.readline()
if not line:
break
#- Type Casting because line is string data type.
try:
scores.append(int(line.strip()))
except ValueError:
print "Exception during Type Casting.- Input %s"%line
return scores
if __name__=="__main__":
scores = main()
showscores(scores)
<强>输出强>:
Exception during Type Casting.- Input
Exception during Type Casting.- Input
Exception during Type Casting.- Input
Exception during Type Casting.- Input
Debug 4: 434
average of scores is= 86.80
使用和语句以及地图功能:
#- Read file content.
with open(file_name, "rb") as fp:
content = fp.read()
#- Get all numbers from the file content by RE and map.
scores = map(int, re.findall("\d+", content))
return scores
答案 4 :(得分:0)
这已经完成。这就是最终的工作:
def showscores(scores):
sum_scores = sum(scores)
average = float(sum_scores // len(scores))
print ("The scores are: " + str(scores))
print ("Average score: " + str(average))
def main():
scores = []
scores_file = open('scores.txt', 'r')
line_list = list(scores_file.readlines())
scores_file.close()
i = 0
while i < len(line_list):
scores.append(int(line_list[i].strip()))
i += 1
showscores(scores)
main()