根据排名重新映射数据

时间:2018-11-04 20:20:14

标签: python python-3.x

我有以下内容:

d = {"a":3,"b":2,"c":3,"d":2,"e":2,"f":3,"g":4, "h":6}

m = {v: i+1 for i,v in enumerate(sorted(set(d.values()),reverse=True))}
r = {k:m[d[k]] for k in d}  

其中r是:

{'a': 3, 'd': 4, 'b': 4, 'c': 3, 'e': 4, 'f': 3, 'g': 2, 'h': 1}

因此,“ h”在d中具有最高值6,因此将其重新映射为r中的1。然后,“ g”的排名第二,因为它的值第二高,即d中的4。

我的解决方案工作正常,但我想知道是否有更优雅的解决方案。

3 个答案:

答案 0 :(得分:2)

Python字典不保持顺序。如果您需要OrderedDict

使用Counter获得排名。然后将其转换为元组列表或OrderedDict

from collections import Counter, OrderedDict

d = {"a":3,"b":2,"c":3,"d":2,"e":2,"f":3,"g":4, "h":6}
c = Counter(d)

# if you want a list of tuples
ranked_list = [(pair[0],rank+1) for rank,pair in enumerate(c.most_common())]
# [('h', 1),('g', 2),('f', 3),('a', 4),('c', 5),('b', 6),('d', 7), ('e', 8)]

# if you want a dict:
ranked_dict = OrderedDict(ranked_list)
# OrderedDict([('h', 1),('g', 2),('f', 3),('a', 4),('c', 5),('b', 6),('d', 7), ('e', 8)])

答案 1 :(得分:0)

您可以使用此:

d = {"a":3,"b":2,"c":3,"d":2,"e":2,"f":3,"g":4, "h":6}

# sort the dictionary items by -value, throw away old value and use the
# enumerate position starting at 1 instead - no backreferencing in the old
# dict needed here

k = {k:idx for idx,(k,_) in enumerate(sorted(d.items(), key = lambda x:-x[1]),1)}

print(k)

输出:

{'h': 1, 'g': 2, 'a': 3, 'c': 4, 'f': 5, 'b': 6, 'd': 7, 'e': 8}

答案 2 :(得分:0)

fetch('http://localhost:8888/o/token',
       {
         method: 'POST',
         headers: {
           'Accept': 'application/json',
           'Content-Type': 'application/x-www-form-urlencoded;'
         },
         body: qs.stringify({
           'grant_type': 'password',
            'username': 'MyUserNameSettedInApi',
            'password': 'PasswordSettedInApi',
            'client_id': 'MyClientId',
            'client_secret': 'MyClientSecret',
         })
       })