多行文本文件的平均值,Python 3

时间:2017-01-30 22:05:55

标签: python tuples

我有一个.txt文件,其中包含我需要计算平均值的等级线。我真的碰到了一堵墙,弄清楚如何让平均功能迭代文本文件的每一行。出于某种原因,如果存在奇数行,则会出现语法错误。当行数量为偶数时,python将返回每个其他行。这是我的代码。

with open('grades.txt','r') as source:
def toNumbers():
    global t
    g = source.readline()
    t = eval(g)
def sumList(variable):
    a = sum(variable)/len(variable)
    print('average:', round(a))
for lines in source:
    toNumbers()
    sumList(t)

感谢。

1 个答案:

答案 0 :(得分:0)

您应该将tonumbers()功能修改为:

def toNumbers(line):
    res = eval(line)
    return res

你的主要循环是:

for line in source.read():
    t = toNumbers(line)
    sumList(t)

一般情况下,不建议使用global,您应该尝试使用参数并返回结果来绕过它。希望我帮忙!