查找一系列dicts中的最小值

时间:2011-06-18 11:39:26

标签: python

我有一个如下数组:

people = [{'node': 'john', 'dist': 3}, 
          {'node': 'mary', 'dist': 5}, 
          {'node': 'alex', 'dist': 4}]

我想计算所有'dist'键的最小值。例如,在上面的例子中,答案是3。

我写了以下代码:

min = 99999
for e in people:
    if e[dist] < min:
        min = e[dist]
print "minimum is " + str(min)

我想知道是否有更好的方法来完成这项任务。

4 个答案:

答案 0 :(得分:8)

使用min功能:

minimum = min(e['dist'] for e in people)
# Don't call the variable min, that would overshadow the built-in min function
print ('minimum is ' + str(minimum))

答案 1 :(得分:3)

min(x['dist'] for x in people)

答案 2 :(得分:3)

您可以使用生成器表达式创建包含所有键的列表,然后使用内置的min函数:

min(x['dist'] for x in people)

答案 3 :(得分:0)

min(people, key=lambda x:x['dist'])['dist']