python - 我想对文档进行排名并将它们存储在 python 的列表中

标签 python sorting

我只是Python的初学者。我有文档 score= {1:0.98876, 8:0.12245, 13:0.57689} 存储在字典中。键对应一系列文档 id,值对应每个文档 id 的分数。如何根据分数对文档进行排名?

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

我已经使用上面的方法找到了最大值,其返回:

(0.98876,1)

但我想要的是对文档进行排序并存储在列表中:

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

最佳答案

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

应该可以解决问题

字典中元素的顺序未定义,因此排序结果必须存储在列表中(或 OrderedDict )。

您应该使用 items() 将其转换为元组列表。使用sorted(),你可以对它们进行排序,key参数告诉它根据第二个元组元素的倒数进行排序。

完整示例:

>>> 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)]

如果您确实想这样做,这还展示了如何反转元组中的元素。

关于python - 我想对文档进行排名并将它们存储在 python 的列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3142987/

相关文章:

python - 如何使用(最好)正则表达式模式将一列中的值拆分为两列?

python - Django URL、模板、模型和 View 的命名约定

C 中的计数排序显然有效,但二进制搜索无效

sorting - Solr 中的负提升

arrays - 二维数组排序问题

Python:迭代同时包含相似值的列表和字典的有效方法

python - 如何使用用户提供的图像将 python 脚本作为 Web 服务运行?

python - 如何修复 'ValueError: input tensor must have rank 4' ?

java - 无法按升序对列表进行排序

Java/Libgdx 自动磁贴