简体   繁体   中英

Finding minimum value in an array of dicts

I have an array like the following:

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

I want to compute the minimum of all the 'dist' keys. For instance, in the above example, the answer would be 3.

I wrote the following code:

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

I am wondering if there is a better way to accomplish this task.

Use the min function:

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))
min(x['dist'] for x in people)

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM