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

问题描述 投票:-1回答:1

我从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

你们任何人都知道如何做到这一点?我尝试了一些代码,但它们只是没有用。

python python-3.x
1个回答
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))
© www.soinside.com 2019 - 2024. All rights reserved.