我有词典列表
rows = [
{'name': 'someone1', 'score': 20},
{'name': 'someone2', 'score': 90},
{'name': 'someone3', 'score': 60},
]
我想根据得分添加另一个字段排名。目前,我正在执行多个步骤。
# Step 1: sort it
rows_sorted = sorted(rows, key=lambda x: x['score'], reverse=True)
# Step 2: add rank field
[row.setdefault('rank', idx) for idx, row in enumerate(rows_sorted, start=1)]
所以现在我所需的输出在rows_sorted中,就像
[{'name': 'someone2', 'score': 90, 'rank': 1},
{'name': 'someone3', 'score': 60, 'rank': 2},
{'name': 'someone1', 'score': 20, 'rank': 3}]
有什么方法可以一步一步完成吗?
答案 0 :(得分:2)
rows = [
dict(row, rank=idx + 1)
for idx, row in enumerate(sorted(rows, key=lambda x: -x['score']))
]
答案 1 :(得分:0)
尝试一下:
all_scores = sorted([k['score'] for k in rows], reverse = True)
for i in rows:
i['rank'] = all_scores.index(i['score'])+1
输出:
>>> rows
[{'name': 'someone1', 'score': 20, 'rank': 3}, {'name': 'someone2', 'score': 90, 'rank': 1}, {'name': 'someone3', 'score': 60, 'rank': 2}]