开发者

I want to rank document and store them in a list in python

I am just a beginner in python. I have document score= {1:0.98876, 8:0.12245, 13:0.57689} which is stored in dictionary. The keys are corresponding to a series of document id and the 开发者_开发问答values are corresponding to the score for each document id. How do I rank the document based on the scores?

inverse=[(value, key) for key, value in score.items()]
fmax=max(inverse)

I already found the maximum values by using the method above which return:

(0.98876,1)

But what I want is to rank the documents and store in a list:

{(0.98876,1),(0.57689,13),(0.12245,8)}


sorted(score.items(), key=lambda x:-x[1])

should do the trick

The order of the elements in a dictionary is not defined, so the result of the sorting has to be stored in a list (or an OrderedDict).

You should convert it to a list of tuples using items(). With sorted() you can sort them, the key parameter tells it to sort according to the inverse of the second tuple element.

Full example:

>>> score= {1:0.98876, 8:0.12245, 13:0.57689}
>>> sorted(score.items(), key=lambda x:-x[1])
[(1, 0.98875999999999997), (13, 0.57689000000000001), (8, 0.12245)]
>>> print [(y,x) for (x,y) in _]
[(0.98875999999999997, 1), (0.57689000000000001, 13), (0.12245, 8)]

This also shows how to reverse the elements in the tuple if you really want to do that.


if you want to modify original list inverse then use inverse.sort(reverse=True).
If you want to produce a new list and leave original list untouched, use sorted(inverse, reverse=True).

You don't need an intermediate list, however, just use score:

>>> sorted(score.items(), key=lambda x: x[1], reverse=True)
[(1, 0.98876), (13, 0.57689), (8, 0.12245)]


After your inverse method, this would do the trick:

ranked = inverse.sort()

And here's some more info on sorting in python: http://wiki.python.org/moin/HowTo/Sorting/


Sort the inverse list:

inverse.sort()

This will return the list in ascending order, if you want it in reverse order, reverse it also:

inverse.reverse()


use this: inverse.sort(reverse=True)

have a look here for more info on sorting


if you want rank itens in dict:

score = {1:0.98876, 8:0.12245, 13:0.57689}
# get a list of items...
list = score.items()
print list
[(8, 0.12245), (1, 0.98875999999999997), (13, 0.57689000000000001)]

# Sort items.
list.sort()
print list 
[(1, 0.98875999999999997), (8, 0.12245), (13, 0.57689000000000001)]
# reverse order
list.reverse()
print list
[(13, 0.57689000000000001), (8, 0.12245), (1, 0.98875999999999997)]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜