简体   繁体   English

如何获得一个字典的多个最小/最大值?

[英]How to get more than one smallest /largest values of a dictionary?

Like if i create a dictionary using the following script: 就像我使用以下脚本创建字典一样:

r_lst = {}
for z in df.index:
  t = x.loc[0, 'sn']
  s = df.loc[z, 'rv']
  slope, intercept, r_value, p_value, std_err = stats.linregress(t,s)
  r_lst.setdefault(float(z),[]).append(float(r_value))

The resultant dictionary loos like this 结果字典像这样

{4050.32: [0.29174641574734467],
 4208.98: [0.20938901991887324],
 4374.94: [0.2812420188097632],
 4379.74: [0.28958742731611586],
 4398.01: [0.3309140298947313],
 4502.21: [0.28702220304639836],
 4508.28: [0.2170363811575936],
 4512.99: [0.29080133884942105]}

Now if i want to find the smallest or largest values of the dictionary then i just have to use this simple command min(r_lst.values()) or max(r_lst.values()) . 现在,如果我想查找字典的最小或最大值,则只需使用此简单命令min(r_lst.values())max(r_lst.values())

What if i want the three lowest values or three highest values.? 如果我要三个最低值或三个最高值怎么办? Then how can i get that? 那我该怎么办呢? I saw some questions here but none of them answers what i'm asking for. 我在这里看到了一些问题,但没有一个回答我的要求。

Just use sorted() : 只需使用sorted()

sorted(r_lst.values())

Or in reverse order: 或以相反的顺序:

sorted(r_lst.values(), reverse=True)

So to get the 3 largest values: 因此,要获得3个最大值:

sorted(r_lst.values(), reverse=True)[:3]

Yields: 产量:

[[0.3309140298947313], [0.29174641574734467], [0.29080133884942105]]

You can use heapq.nsmallest / heapq.nlargest : 您可以使用heapq.nsmallest / heapq.nlargest

import heapq

res = heapq.nsmallest(3, d.values())

# [[0.20938901991887324], [0.2170363811575936], [0.2812420188097632]]

To extract as a flat list, you can use itertools.chain : 要提取为平面列表,可以使用itertools.chain

from itertools import chain
import heapq

res = list(chain.from_iterable(heapq.nsmallest(3, d.values())))

# [0.20938901991887324, 0.2170363811575936, 0.2812420188097632]

These heapq solutions will have time complexity O(( n - k )*log n ) versus O( n log n ) for solutions requiring a full sort. 对于需要完整排序的解决方案,这些heapq解决方案的时间复杂度为O(( n - k )* log n )与O( n log n )。

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

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