[早上好,请提供一张我要返回的职位(排名)表学生分数。我到处搜索,但没有得到任何改善。我以为我可以通过排序来做到这一点,但事实并非如此。这是表格:
名称分数位置
David 89 3rd
詹姆斯56第五]
Matt 72 4th
约翰91第一节
艾娃56第五]
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)
[早上好,请给我一张桌子,试图返回学生分数的位置(排名)。我到处搜索,但没有得到任何改善。我以为可以用...
不是最漂亮的代码,但是我认为这满足了您的要求:
from collections import Counter
score = [89, 56, 72, 91, 56, 91]
score_set = sorted(list(set(score)), reverse=True) # unique score
dico = dict((v, i + 1) for i, v in enumerate(score_set)) # position of unique score
count = Counter(score) # occurence of each score
total = 1 # indice to get the current position in the score
# update the dico by counting the number of duplicate.
for k, v in sorted(dico.items(), key=lambda x: x[1]): # sort the dico by the value (rank without duplicate)
count_ = count[k]
dico[k] = total
total += count_ # take into account potential duplicate
position = [dico[e] for e in score] # apply the dict to our original list
print(position) # et voilà