Python中列表的字典中的miminum length / max值 [英] Python miminum length/max value in dictionary of lists

查看:167
本文介绍了Python中列表的字典中的miminum length / max值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我有一个字典,如下所示:

  d = {'a':[4,2],'b':[3,4],'c':[4,3],'d' [4,3],'e':[4],'f':[4],'g':[4]} 

我想获得与字典d中最小长度相关联的键以及具有最大值的键。



在这种情况下,长度最小的密钥(该字典中列表的最小长度)应该返回

 'e,'f','g'

价值最大的人(每个列表中的整数的总和)应该返回

 'b''''

我尝试过

  min_value = min(dict.itervalues())
min_keys = [k for d in如果dict [k] == min_value]

但是这并不能给我我想要的结果。



任何想法?



谢谢!

解决方案

  def get_smallest_length(x):
return [k for x in x.keys()if len(x.get(k))== min([len(n)for n in x.values()]]]

def get_largest_sum(x):
return [k for x in x.keys()中的sum如果sum(x.get(k))== max([sum(n)for n in x.values() ])]

x = {'a':[4,2],'c':[4,3],'b' :[3,4],'e':[4],'d':[4,3],'g':[4],'f':[4]}

print get_smallest_length(x)
print get_largest_sum(x)

返回:

  ['e','g','f'] 
['c','b','d']


Had to re-write the question due to changed requirements.

I have a dictionary such as the following:

d = {'a': [4, 2], 'b': [3, 4], 'c': [4, 3], 'd': [4, 3], 'e': [4], 'f': [4], 'g': [4]}

I want to get the keys that are associated with the smallest length in the dictionary d, as well as those that have the maximum value.

In this case, the keys with the smallest length (smallest length of lists in this dictionary) should return

'e, 'f', 'g'

And those with the greatest value(the sum of the integers in each list) should return

'b' 'c'

I have tried

min_value = min(dict.itervalues())
min_keys = [k for k in d if dict[k] == min_value]

But that does not give me the result I want.

Any ideas?

Thanks!

解决方案

def get_smallest_length(x):
    return [k for k in x.keys() if len(x.get(k))==min([len(n) for n in x.values()])]

def get_largest_sum(x):
    return [k for k in x.keys() if sum(x.get(k))==max([sum(n) for n in x.values()])]

x = {'a': [4, 2], 'c': [4, 3], 'b': [3, 4], 'e': [4], 'd': [4, 3], 'g': [4], 'f': [4]}

print get_smallest_length(x)
print get_largest_sum(x)

Returns:

['e', 'g', 'f']
['c', 'b', 'd']

这篇关于Python中列表的字典中的miminum length / max值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆