Python通过字典(dict)中value获取前n个最大的元素方法及示例代码

Python通过字典(dict)中value获取前n个最大的元素方法及示例代码,第1张

Python通过字典(dict)中value获取前n个最大的元素方法及示例代码

本文主要介绍Python中,根据字典(Dictionary)中value的大小,来获取字典中获取前n个最大的元素的方法,以及相关的示例代码。

1、使用 collections.defaultdict实现
from collections import defaultdict
pN ={'dave': 10, 'jacinta': 10, 'james': 8, 'john': 6, 'jack': 3, 'sam': 2}
#交换key和value
dct = defaultdict(list)

for k, v in pN.items():
  dct[v].append(k)
#排序
for k, v in sorted(dct.items(), reverse=True):
  print(k, ', '.join(v))
#返回前n个元素
def top_n(d, n):
  dct = defaultdict(list) 
  for k, v in d.items():
    dct[v].append(k)      
  return sorted(dct.items())[-n:][::-1]

top_n(pN, 3)

输出结果:
[(10, ['dave', 'jacinta']), (8, ['james']), (6, ['john'])]
2、使用max来实现
pN ={'dave': 10, 'jacinta': 10, 'james': 8, 'john': 6, 'jack': 3, 'sam': 2}
def top_n_scores(n, score_dict):
  ''' returns the n scores from a name:score dict'''
  lot = [(k,v) for k, v in pN.items()] #make list of tuple from scores dict
  nl = []
  while len(lot)> 0:
      nl.append(max(lot, key=lambda x: x[1]))
      lot.remove(nl[-1])
  return nl[0:n]   
top_n_scores(4, pN)  

输出结果:
[('dave', 10), ('jacinta', 10), ('james', 8), ('john', 6)]
我的实践

返回employee潜力最低或最高值
规则1:需返回2个值
规则2:第一优先返回最低的2个值,且低于35
规则3:第一优先的两个值产生1个或者产生0个时,返回1个最高值或2个最高值

# 返回employee潜力最低或最高值
### 规则1:需返回2个值
### 规则2:第一优先返回最低的2个值,且低于35
### 规则3:第一优先的两个值产生1个或者产生0个时,返回1个最高值或2个最高值


#pN ={'dave': 100, 'jacinta': 55, 'james': 48, 'john': 46, 'jack': 43, 'sam': 42}
#pN ={'dave': 100, 'jacinta': 55, 'james': 38, 'john': 36, 'jack': 43, 'sam': 42}
pN ={'dave': 100, 'jacinta': 55, 'james': 8, 'john': 6, 'jack': 3, 'sam': 2}

def bottom_n_scores(n, pN):
  ''' returns the n scores from a name:score dict'''
  lot = [(k,v) for k, v in pN.items()] #make list of tuple from scores dict
  nl = []
  while len(lot)> 0:
      nl.append(min(lot, key=lambda x: x[1]))
      lot.remove(nl[-1])
  return nl[0:n]

def top_n_scores(n, pN):
  ''' returns the n scores from a name:score dict'''
  lot = [(k,v) for k, v in pN.items()] #make list of tuple from scores dict
  nl = []
  while len(lot)> 0:
      nl.append(max(lot, key=lambda x: x[1]))
      lot.remove(nl[-1])
  return nl[0:n]


def pp_rules_function(pN):
    potential_list = []
    if bottom_n_scores(2, pN)[0][1]<=35:
        potential_list.append(bottom_n_scores(2, pN)[0])
        if bottom_n_scores(2, pN)[1][1]<=35:
            potential_list.append(bottom_n_scores(2, pN)[1])
        else:
            potential_list.append(top_n_scores(2, pN)[0])
    else:
        potential_list.append(top_n_scores(2, pN)[0])
        potential_list.append(top_n_scores(2, pN)[1])


    print(potential_list)
    return potential_list

pp_rules_function(pN)

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/4697740.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-07
下一篇 2022-11-07

发表评论

登录后才能评论

评论列表(0条)

保存