gpt4 book ai didi

Python 序数排序

转载 作者:行者123 更新时间:2023-12-02 02:58:04 25 4
gpt4 key购买 nike

早上好,我有一张表,我正在尝试返回位置(排名)学生的成绩。我已经到处寻找但没有找到更好的东西。我以为我可以通过排序来做到这一点,但事实并非如此。这是表格:

Name       Score    Position 

David 89 3rd
James 56 5th
Matt 72 4th
John 91 1st
Iva 56 5th
Anna 91 1st

我尝试编写此代码,但它没有处理重复项

score = [89, 56, 72, 91, 56,91]
order = sorted(list(set(score)), reverse=True)
position = []

for n in score:
position.append(order.index(n) + 1)

print(position)

最佳答案

如果你愿意使用外部库,我只能推荐ranking :

import ranking

# Each player and their scores.
score_list = [
('David', 89),
('James', 56),
('Matt', 72),
('John', 91),
('Iva', 56),
('Anna', 91),
]

# Helper for accessing a score record's score,
# defined here as we need it twice.
get_score = lambda pair: pair[1]

# Sort the scores in place; required by `ranking`.
score_list.sort(key=get_score, reverse=True)

# Define a format string; handy for formatting both the header and the scores.
format_str = "{player:10} {score:<10} {rank}"

# Print header.
print(format_str.format(player="Player", score="Score", rank="Position"))

# Rank and print.
for rank, (player, score) in ranking.Ranking(score_list, key=get_score, start=1):
print(format_str.format(rank=rank, player=player, score=score))

输出

Player       Score        Position
John 91 1
Anna 91 1
David 89 3
Matt 72 4
James 56 5
Iva 56 5

关于Python 序数排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60636953/

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