python中dict列表中的前k [英] Top-k on a list of dict in python

查看:30
本文介绍了python中dict列表中的前k的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此示例中,是否有一种简单的方法来执行最大k个key:values对

Is there an easy way to perform the max k number of key:values pair in this example

s1 = {'val' : 0}
s2 = {'val': 10}
s3 = {'val': 5}
s4 = {'val' : 4}
s5 = {'val' : 6}
s6 = {'val' : 7}
s7 = {'val' : 3}
shapelets = [s1,s2,s3,s4,s5,s6,s7]

我想在Shapelets列表中获取最多5个数字,因为它包含名称为"val"的键,并为其分配了值.这里的解决方案在于解析dict元素列表,并获取它的最大n个数字(在这种情况下,最大为5个值)

I want to get the max 5 numbers in the shapelets list, knowing that it contains a key of name "val" and to which a value is assigned. The solution here resides in parsing through the list of dict elements and get the max n numbers of it ( in this case the max 5 values )

什么是简单的解决方案,python中的运算符库是否支持这种操作?

What can be a simple solution, does operator library in python supports such operation ?

推荐答案

这是一个有效的示例:

s1 = {'val': 0}
s2 = {'val': 10}
s3 = {'val': 5}
s4 = {'val': 4}
s5 = {'val': 6}
s6 = {'val': 7}
s7 = {'val': 3}
shapelets = [s1, s2, s3, s4, s5, s6, s7]

print(sorted(shapelets, key=lambda x: x['val'])[-5:])

这篇关于python中dict列表中的前k的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆