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

时间:2015-12-08 11:03:14

标签: python sorting average

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

1 个答案:

答案 0 :(得分:0)

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

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