从文本文件读取时计算学生平均分数的语法错误

Syntax error calculating the average of student marks while reading from a text file

f = open('studMarks.txt', 'r')
marks = 0
# Sort out names, split the words then sort which order
    for line in f:
    words = line.split()
    fname = words[0]
    lname = words[1]
    print(f"{lname},{fname}")
f.close()

f = open('studMarks.txt', 'r')
sum = 0
count = 0
for line in f:
    count += 1
    sum += float(line.split()[2])
    n = []
average = sum/count

print(f"{average}")

当使用 for 循环时,它似乎显示 64.3 的值,我认为这是整个学生列表的总分和所有分数的平均值。

我需要生成在同一行显示学生姓名和平均分的输出。我可以为名字做,但我不能为平均值做,因为我不断出错。不知道输入什么

这是一个有趣的问题。 据我了解,您有一个如下所示的文本文件: Johnny Ly 90 100 Adam Best 80 30 Tim Smith 10 20 在名为 studentMarks2.txt 的文件中 并想要这样的输出: Johnny_Ly 95.0 Adam_Best 55.0 Tim_Smith 15.0 如果这是真的,那么可以使用没有 pandas 或 csv 的代码来完成 尽管这些会使这变得容易得多。

fileContents = []

with open('studMarks2.txt','r') as f:
    fileContents = f.read().split()
    

students = dict()

names = []
for content in fileContents:
    if content.isnumeric():
        studentKey = '_'.join(names)
        currentScore = students.get(studentKey,[])        
        newScore = currentScore + [float(content)]
        students.update({studentKey:newScore})        
    else:
        if len(names) == 2:
            names.clear()
            names.append(content)
        else:
            names.append(content)
            
for student,scores in students.items():
    avg = sum(scores)/len(scores)
    print(student,avg,end=' ')

崩溃了 这部分阅读内容并在白色上拆分space

fileContents = []    
    with open('studMarks2.txt','r') as f:
        fileContents = f.read().split()

这部分然后遍历内容 将名称作为键存储在字典中并将分数放入列表中

students = dict()        
    names = []
    for content in fileContents:
        if content.isnumeric():
            studentKey = '_'.join(names)
            currentScore = students.get(studentKey,[])        
            newScore = currentScore + [float(content)]
            students.update({studentKey:newScore})        
        else:
            if len(names) == 2:
                names.clear()
                names.append(content)
            else:
                names.append(content)

最后它遍历字典并在一行上输出平均值

for student,scores in students.items():
    avg = sum(scores)/len(scores)
    print(student,avg,end=' ')

下面是完整的解决方案。 with open 行是上下文管理器,可确保文件在您退出该块后立即关闭。您应该习惯使用这种风格,因为这是安全的做法 I/O。其余的只是沼泽标准 Python.

marks=dict()
with open('studMarks.txt', 'r') as f:
    for line in f:
        words = line.split()
        fname = words[0]
        lname = words[1]
        score = int(words[2])
        key = f'{fname} {lname}'
        count_key = f'{fname} {lname}_count'
        latest_score = score + (marks.get(key)[0] if marks.get(key) else 0)
        latest_count = 1 + (marks.get(key)[1] if marks.get(key) else 0)
        marks[key] = (latest_score, latest_count )
for name, value in marks.items():
    print(f'{name} : {value[0]/value[1]}')