在字典中对值进行排名(并正确地保护了ex-equeques) [英] Ranking values in a Dictionary (and taking care of ex-aequos correctly)

查看:72
本文介绍了在字典中对值进行排名(并正确地保护了ex-equeques)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对字典中的值进行排名.

I would like to rank the values in a dictionary.

例如,我有这个字典:{"A": 10, "B: 3, "C": 8, "D": 3, "E": 2} 结果应类似于:{"E": 1, "B": 2, "D": 2, "C": 4, "A": 5}

For instance, I have this dictionary: {"A": 10, "B: 3, "C": 8, "D": 3, "E": 2} The result should look like: {"E": 1, "B": 2, "D": 2, "C": 4, "A": 5}

请注意,由于BD并列在 two 位置,因此D被列为第四.因此,没有位置三个.

Please note that D is ranked as fourth because B and D are tied at position two. Hence, there is no position three.

在其他线程中也已经给出了类似的解决方案,但是它们没有以传统方式考虑前任职位: Python排名字典返回排名

Similar solutions have already been given in other threads, however they did not take into account ex-aequo positions in the traditional way: Adding a rank to a dict in python and Python Ranking Dictionary Return Rank

推荐答案

首先根据数字按升序对数据进行排序,就像这样

First sort the data in ascending order based on the number, like this

>>> data = {"A": 10, "B": 3, "C": 8, "D": 3, "E": 2}
>>> s_data = sorted(data.items(), key=lambda item: item[1])
>>> s_data
[('E', 2), ('D', 3), ('B', 3), ('C', 8), ('A', 10)]

现在,对于每个处理的元素,

Now, for every element processed,

  • 如果它与先前的元素不同,则应按直到现在为止已处理的相似元素的数量来增加排名

  • if it is not the same as the previous element then the rank should be incremented by the number of similar elements processed till now

如果相同,则只需将当前元素视为相似元素

if it is the same, then simply count the current element as a similar element

要实现此目的,请初始化一些变量,例如

To implement this, initialize few variables, like this

>>> rank, count, previous, result = 0, 0, None, {}

然后继续检查当前元素是否不等于前一个元素,如果为true,则将rank递增类似元素出现的次数.

then keep checking if the current element is not equal to the previous element and if it is true, increment rank by the number of times the similar elements occured.

>>> for key, num in s_data:
...     count += 1
...     if num != previous:
...         rank += count
...         previous = num
...         count = 0
...     result[key] = rank

现在,result将具有您想要的结果.

Now, result will have the result you wanted.

>>> result
{'D': 2, 'C': 4, 'E': 1, 'B': 2, 'A': 5}

这篇关于在字典中对值进行排名(并正确地保护了ex-equeques)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆