本文主要介绍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)