我将给出一些演示代码:
# -*- coding: utf-8 -*-
import csv
from collections import defaultdict
from statistics import mean
class_file = ''
open_file = open(class_file)
csv_file = csv.reader(open_file)
def main():
# First, use student name to group by all scores, this will
# generate structure like this:
# {
# 'Andrew': [1, 2, 3, 4, 5]),
# 'Luck': [10, 20]),
# }
score_groups = defaultdict(list)
for name, score in csv_file:
score_groups[name].append(int(score))
# Secondary, use the 3 latest socres only
l3_score_groups = [(key, value[-3:]) for key, value in score_groups.items()]
print('1. Alphabetical order with each students highest score.')
l3_highest_score_groups = [(key, max(values)) for key, values in l3_score_groups]
for name, score in sorted(l3_highest_score_groups, key=lambda x: x[0]):
print(name, score)
print('2. By the highest score, highest to lowest.')
l3_highest_score_groups = [(key, max(values)) for key, values in l3_score_groups]
for name, score in sorted(l3_highest_score_groups, key=lambda x: x[1], reverse=True):
print(name, score)
print('3. Average score, highest to lowest.')
l3_aver_score_groups = [(key, mean(values)) for key, values in l3_score_groups]
for name, score in sorted(l3_aver_score_groups, key=lambda x: x[1], reverse=True):
print(name, score)
if __name__ == '__main__':
main()
以下是上面使用的技术:
希望能帮助到你.