繁体   English   中英

使用 Python 从字典列表中获取 N 个最大的键值

[英]Get the N largest key value from a list of dictionary with Python

我可以知道是否有直接/紧凑的方法来从具有 Python 的字典列表中提取 N 个最大键值

虽然下面的方法产生了理想的结果,但我想知道是否有更好的选择。

from heapq import nlargest
from operator import itemgetter
dls=[{'dname': 'a', 'text': 'CC',  'dscore': 0.3},
 {'dname': 'b', 'text': 'CC',  'dscore': 0.1},
 {'dname': 'c', 'text': 'CC',  'dscore': 0.9},
 {'dname': 'd', 'text': 'CC',  'dscore': 0.2},
 {'dname': 'e', 'text': 'CC',  'dscore': 0.102}]



ls=[d['dscore'] for d in dls ]

nlargest=nlargest(3, range(len(ls)), key=ls.__getitem__)
print(itemgetter(*sorted(nlargest))(dls))

Output

({'dname': 'a', 'text': 'CC', 'dscore': 0.3}, {'dname': 'c', 'text': 'CC', 'dscore': 0.9}, {'dname': 'd', 'text': 'CC', 'dscore': 0.2})

如果您将字典列表转换为一个完整的字典,并以dname作为键,则可能会更容易。 然后,您可以使用list(dict.keys)以列表形式访问字典的键,对键列表进行排序,然后使用列表遍历字典。 但是,这是一种迂回的方式,可能不是您想要的。

您是否认为性能会成为您现在或将来拥有的数据集的问题。 如果不专注于代码的可理解性而不是速度。 将数据的存储方式与数据的处理隔离开来。
这样,如果数据结构必须更改代码的 rest 则不会。 这打开了关于使用哪种技术(面向对象,功能......)的蠕虫罐,这是另一个问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM