gpt4 book ai didi

python - 得分前五名

转载 作者:行者123 更新时间:2023-11-30 22:05:52 26 4
gpt4 key购买 nike

我在学校遇到了一个编程挑战,我制作了一个游戏,最后,它打印了有史以来的前五名分数。我已经能够让它打印前五个分数,但我不知道如何让它打印带有用户名的分数。代码是:

with open("login.csv") as f:
print(" ")
print(" ")
print("Usernames and scores:")
reader=csv.reader(f)
scores=(row[-1] for row in reader)
topscore=sorted(scores, reverse=True)
top5=topscore[:5]
print(top5)

我得到的输出是:

Usernames and scores:
['82', '80', '66', '64', '62']

但是我想要的输出是:

Usernames and scores:
Dylan, 82
f, 80
Farai, 66
Dylan, 64
Dylan, 62

任何帮助迪伦

我错过了这一点,但列是名称、密码、分数。抱歉错过了伙计们。

最佳答案

您可以使用一个关键函数对行进行排序,该函数允许基于最后一列进行排序:

with open("login.csv") as f:
print(" ")
print(" ")
print("Usernames and scores:")
reader=csv.reader(f)
topscore=sorted(reader, key=lambda row: int(row[-1]), reverse=True)
top5=topscore[:5]
print('\n'.join(', '.join((username, score)) for username, _, score in top5))

关于python - 得分前五名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52877000/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com