我有一个数组
array = [('item1',90),('item2',76),('item3',83),('item4',90)]
我想给它排名
ranking = [(0,'item1'),(0,'item4'),(2,'item3'),(3,'item2')] // (1)
到目前为止,这是我使用ranking完成的工作:
from ranking import *
>>> array.sort(key=lambda x: x[1],reverse = True)
>>> print [i for i in list(Ranking([i[1] for i in array]))]
这是我得到的:
[(0, 90), (0, 90), (2, 83), (3, 76)] // (2)
谁能帮助我从(2)达到(1)?我真的不需要使用排名.我接受任何其他解决方案.
解决方法:
array = [('item1',90),('item2',76),('item3',83),('item4',90)]
srt = sorted(array,key=lambda x: x[1], reverse=True)
rankings = []
rank = 0
from itertools import groupby
for k,v in groupby(srt,lambda x: x[1]): # group by score
grp = [(rank,tup[0]) for tup in v] # get item tup[0] and put it in a tuple with the rank
rankings += grp
rank += len(grp) # increase rank for next grouping
print(rankings)
[(0, 'item1'), (0, 'item4'), (2, 'item3'), (3, 'item2')]