如何汇总不同行中的分数并在Python中返回最大总分数?

时间:2019-04-14 12:08:24

标签: python python-3.x

我从CSV文件中获取的数据如下:

csv_reader = [['Ali', '34'], ['Ali', '20'], ['Ali', '12.34'], ['Ben', '100.98'], ['Jack', '12.34'], ['Jack', '14.34'], ['Jack', '33'], ['Orlaith', '55.66'], ['Orlaith', '2']]

我想总结每个人的分数,看看谁的分数最高。所以我期望如下:

Ben has the highest total score of 100.98

任何人都知道该怎么做?我已经尝试了一些代码,但是它们根本没有用。

1 个答案:

答案 0 :(得分:1)

csv_reader = [['Ali', '34'], ['Ali', '20'], ['Ali', '12.34'], ['Ben', '100.98'], ['Jack', '12.34'], ['Jack', '14.34'], ['Jack', '33'], ['Orlaith', '55.66'], ['Orlaith', '2']]
cumulative = dict()
for person, score in csv_reader:
    cumulative[person] = cumulative.get(person, 0) + float(score)

max_score = max(cumulative.values())
max_score_persons = [person for person, score in cumulative.items() if score == max_score]

max_score_persons_string = ', '.join(max_score_persons)
print("{0} has the highest total score of {1}".format(max_score_persons_string, max_score))