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)
  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值