Python-在字典列表中获取最大值 [英] Python - Get max value in a list of dict

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

问题描述

我有一个具有这种结构的数据集:

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.

非常感谢

推荐答案

遍历列表中的所有字典;遍历每个字典,获取值.取其中的max.使用内置的构造函数,可以使运行时系统尽最大可能为您优化事情.

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.

在Python 2.7中:

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)

输出:

MAX 4.2114

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

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