Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何按平均顺序对记事本数据进行排序?_Python_Sorting_Average - Fatal编程技术网

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

Python 如何按平均顺序对记事本数据进行排序?,python,sorting,average,Python,Sorting,Average,到目前为止,我有这个,但我想让它打印我的数据,每个名字旁边都有他们的平均分数 这就是Class1.txt的外观: elif how == 3: with open("Class1.txt") as f: def score(line): return float(line.split(',')[1]) for line in f: string_of_numbers =

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

这就是Class1.txt的外观:

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)))

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

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
现在,打印出结果:

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))))

请显示
Class1.txt
的内容。是所有名称都在一行上,还是每个名称-值对都在一行上?谢谢,但我收到一个错误,说“fobj”不好。我该怎么办?
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