![](/img/trans.png)
[英]How to loop through nested dictionaries and return a specific key value pair using a list that contains values of one of the other keys
[英]store multiple integer values in one list and return best value pair
我有以下三个整数值:
id # identifies the pair
entropy # gives entropy information
len # basicly the length of a string
现在我想存储许多这些值,并选择总体上具有最高熵并且长度值超过n
的前10 n
from collections import defaultdict
d = defaultdict(list)
for id, entropy, len in generateValues:
d[id].append(entropy)
d[id].append(len)
# now get the top 10 values
这可以轻松完成吗?
在构建完这样的字典后,您可以获得前10个值。 虽然如果你在构建字典时找到它们会有更有效的解决方案,如果可能的话。
import heapq
heapq.nlargest(10, (k for k in d if d[k][1] > n), key=lambda k: d[k][0])
要解决您的问题, sorted
支持一个key
参数:
filtered = ((k,v) for k,v in d.iteritems() if v[1] > n) # or filter(d.iteritems(), lambda t: t[1][1] > n)
topTen = sorted(filtered, key=lambda t: t[0], reversed=true)[:10]
对于使用heapq的解决方案来说,这比imho更具可读性(和效率相当)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.