前五名加s

2024-04-19 16:42:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我在学校有一个编程挑战,在那里我做了一个游戏,最后,它打印出所有时间的前五名分数。我已经能够让它打印前五名的分数,但我不知道如何让它打印与用户名一起的分数。代码是:

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

有什么帮助吗 迪伦

我错过了这个,但列去姓名,密码,得分。抱歉错过了,伙计们。你知道吗


Tags: andcsv游戏编程时间分数学校reader
2条回答

似乎你只是通过列表选择了分数。 假设CSV类似于<;username>;,<;score>;,那么下面的方法是否可行?你知道吗

with open("login.csv") as f:
    print(" ")
    print(" ")
    print("Usernames and scores:")
    reader=csv.reader(f)
    scores=(row for row in reader)
    topscore=sorted(scores, reverse=True)
    for score in topscores:
        print(score[0] +",\t" + score[1])

您可以使用键函数对行进行排序,该键函数允许根据最后一列进行排序:

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

相关问题 更多 >