如何按平均顺序排序记事本数据?

2024-09-29 23:16:28 发布

您现在位置:Python中文网/ 问答频道 /正文

elif how == 3:
        with open("Class1.txt") as f:
            def score(line):
                return float(line.split(',')[1])
            for line in f:
                string_of_numbers = []
                print('Total ', (len(string_of_numbers)))
                print('Average ',sum(string_of_numbers)/(len(string_of_numbers)))

到目前为止,我有这个,但我想让它打印我的数据与每个名字与他们的平均分数旁边。你知道吗

这是Class1.txt的样子:

Ben, 10 
John, 4 
Billy, 9
Torin, 10
Charlie, 2
Celyn, 5
Ben, 5
John, 1
Billy, 5
Torin, 5
Charlie, 6
Celyn, 2
Ben, 6
John, 9
Billy, 5 
Torin, 4 
Charlie, 9
Celyn, 1

Tags: oftxtstringlenlinejohnbenprint
1条回答
网友
1楼 · 发布于 2024-09-29 23:16:28

使用字典收集每个名称的所有值:

with open("Class1.txt") as fobj:
    scores = {}
    for line in fobj:
        name, score = line.split(',')
        name = name.strip()
        score = int(score)
        scores.setdefault(name, []).append(score)

现在,打印结果:

for name, values in scores.items():
    print(name, 'Total: {} Average: {:5.2f} '.format(
          len(values), sum(values) / (len(values))))

印刷品:

John Total: 3 Average:  4.67 
Ben Total: 3 Average:  7.00 
Charlie Total: 3 Average:  5.67 
Celyn Total: 3 Average:  2.67 
Torin Total: 3 Average:  6.33 
Billy Total: 3 Average:  6.33 

相关问题 更多 >

    热门问题