python中num_列表的字典中的Python miminum值

Sorry about the question repost...I should have just edited this question in the first place. Flagged the new one for the mods. Sorry for the trouble

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!

解决方案

How about using sorting and lambdas?

#!/usr/bin/env python

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

sorted_by_sum_d = sorted(d, key=lambda key: sum(list(int(item) for item in d[key])))

sorted_by_length_d = sorted(d, key=lambda key: len(d[key]))

print "Sorted by sum of the items in the list : %s" % sorted_by_sum_d

print "Sorted by length of the items in the list : %s" % sorted_by_length_d

This would output:

Sorted by sum of the items in the list : ['a', 'd', 'b', 'f', 'e', 'c']

Sorted by length of the items in the list : ['a', 'd', 'c', 'b', 'f', 'e']

Be aware I changed the initial 'd' dictionary (just to make sure it was working)

Then, if you want the item with the biggest sum, you get the last element of the sorted_by_sum_d list.

(I'm not too sure this is what you want, though)

Edit:

If you can ensure that the lists are always going to be lists of integers (or numeric types, for that matter, such as long, float...), there's not need to cast strings to integers. The calculation of the sorted_by_sum_d variable can be done simply using:

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

sorted_by_sum_d = sorted(d, key=lambda key: sum(d[key]))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值