按值查找用户排名

如何按值查找用户的排名。


data = [

        {

            "playerId": 2,

            "value": 196763.8

        },

        {

           "playerId": 3,

           "value": 196763.8

        },

        {

           "playerId": 44,

           "value": 196764

        }

]

我试过:


index = [ x['playerId'] for x in data ].index(3) #3 playerId

rank = index+1

我得到的排名是:2


对于玩家 Id 2 和 3,排名应为 1(因为值与 196763.8 相同),对于玩家 Id 44,排名应为 2


千万里不及你
浏览 98回答 2
2回答

慕莱坞森

您可以使用 ,即:pandasdf = pd.DataFrame(data)df['rank'] = df['value'].rank(ascending=True, method="min").astype(int)df = df.sort_values(by=['rank']).reset_index(drop=True)for i in range(1, len(df)):&nbsp; &nbsp; last, curr = df.loc[i-1, 'rank'], df.loc[i, 'rank']&nbsp; &nbsp; df.loc[i, 'rank'] = last + 1 if last < curr else lastprint(df)&nbsp; &nbsp;playerId&nbsp; &nbsp; &nbsp;value&nbsp; rank0&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;2&nbsp; 196763.8&nbsp; &nbsp; &nbsp;11&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;3&nbsp; 196763.8&nbsp; &nbsp; &nbsp;12&nbsp; &nbsp; &nbsp; &nbsp; 44&nbsp; 196764.0&nbsp; &nbsp; &nbsp;2

天涯尽头无女友

您需要按以下条件对列表进行排序,并查找某些列表是否与其他列表具有相同的分数,并将它们合并为一个。valueplayer_id这应该可以解决问题:from collections import defaultdictnew_dict = defaultdict(list)for x in data:&nbsp; &nbsp; new_dict[x['value']].append(x['playerId'])&nbsp;&nbsp;rank_list = [[k,v] for k,v in new_dict.items()]# Set reverse=False if lower score is considered higher rankrank_list.sort(key=lambda k: k[0], reverse=True)&nbsp;def get_rank(player_id):&nbsp; &nbsp; for i in range(len(rank_list)):&nbsp; &nbsp; &nbsp; &nbsp; if player_id in rank_list[i][1]:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return i+1 # list is 0 indexed thus +1print('Rank is %s for player id %s' % (get_rank(44), 44))> Rank is 1 for player id 44print('Rank is %s for player id %s' % (get_rank(2), 2))> Rank is 2 for player id 2print('Rank is %s for player id %s' % (get_rank(3), 3))> Rank is 2 for player id 3
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python