python取出字典中最大值_Python-在字典列表中获取最大值

1586010002-jmsa.png

I have a dataset with this structure :

In[17]: allIndices

Out[17]:

[{0: 0, 1: 1.4589, 4: 2.4879},

{0: 1.4589, 1: 0, 2: 2.1547},

{1: 2.1547, 2: 0, 3: 4.2114},

{2: 4.2114, 3: 0},

{0: 2.4879, 4: 0}]

I'd like to identify the highest value inside the list of dict. I do as follow :

def findMax(data):

possiblemax = []

for i in range(len(data)):

temp = list(data[i].values())

tempmax = max(temp)

possiblemax.append(tempmax)

maxValue = max(possiblemax)

return maxValue

It works but I work with a very large dataset and it's a little bit slow. I was wondering of a better and faster way of doing this.

Thanks a lot

解决方案

Iterate over all dictionaries in the list; iterate over each dictionary, grabbing the values. Take max of that. Use the built-in constructors to let the run-time system optimize things for you, as best it can.

In Python 2.7:

ddd = [{0: 0, 1: 1.4589, 4: 2.4879},

{0: 1.4589, 1: 0, 2: 2.1547},

{1: 2.1547, 2: 0, 3: 4.2114},

{2: 4.2114, 3: 0},

{0: 2.4879, 4: 0}]

def findMax(data):

return max(val for item in data for val in item.itervalues())

print "MAX", findMax(ddd)

Output:

MAX 4.2114

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值