【发布时间】:2020-12-30 03:09:43
【问题描述】:
使用 python 3.x 我想获得密集排名(如果排名重复,请不要跳过数字)。我有以下数组根据分数排序
rank_list = [{'Id': 236966, 'score': 91.0}, {'Id': 237241, 'score': 82.0}, {'Id': 237077, 'score': 79.0}, {'Id': 237084, 'score': 78.0}, {'Id': 237080, 'score': 72.0}, {'Id': 237236, 'score': 71.0}, {'Id': 236979, 'score': 71.0}, {'Id': 236909, 'score': 67.0}, {'Id': 237174, 'score': 67.0}, {'Id': 237035, 'score': 66.0}]
我使用下面的代码来计算和分配“排名”字段,但如果排名重复,代码会跳过排名
def rankFunc(e):
return e['score']
rank_list.sort(key = rankFunc, reverse=True)
sorted_scores = [obj['score'] for obj in rank_list]
ranks = [sorted_scores.index(x) for x in sorted_scores]
for index, obj in enumerate(rank_list):
obj['rank'] = ranks[index]+1
当前输出:
排名 = [1, 2, 3, 4, 5, 6, 6, 8, 8, 10]
我希望在不跳过任何数字的情况下分配排名,如下所示,
排名 = [1, 2, 3, 4, 5, 6, 6, 7, 7, 8]
【问题讨论】:
标签: python arrays python-3.x ranking