简体   繁体   English

返回循环字典中键的第一个值条目的最大值

[英]Return maximum of first value entry looping over keys in dictionary

I would like to get the maximum of the first value 10,40 -> 40. I can use this below, but is there a python way in one line instead of the for loop我想获得第一个值 10,40 -> 40 的最大值。我可以在下面使用它,但是在一行中是否有 python 方式而不是 for 循环

    soilLayer[0] = [ 10,    50,    0.3,   1600, 1800,    5,  30 ]
    soilLayer[1] = [ 40,    50,    0.3,   1600, 1800,    5,  30 ]
    heigth = []
    position = 0
    for name in sorted( soilLayer.keys() ):
        heigth.append( soilLayer[name][position] )
    print( max( heigth ) )

first of all, you don't need to sort when you want to find the maximum.首先,当你想找到最大值时,你不需要排序。 You can use operator.itemgetter to get multiple items at once and zip to get the first items.您可以使用operator.itemgetter一次获取多个项目并使用 zip 获取第一个项目。 Then, you can all the max on result.然后,您可以在结果上获得所有max

from operator import itemgetter

max(next(zip(*itemgetter(*soilLayer.keys())(soilLayer)))

There are a few solutions in native Python:原生Python有几个解决方案:

soilLayer = {0: [ 10,    50,    0.3,   1600, 1800,    5,  30 ],
             1: [ 40,    50,    0.3,   1600, 1800,    5,  30 ]}


# turn each list into an iterator, apply next to each, then find maximum
res = max(map(next, map(iter, soilLayer.values())))  # 40

# create a list of first values, then calculate maximum    
res = max(list(zip(*soilLayer.values()))[0])  # 40

# use generator comprehension, most Pythonic
res = max(x[0] for x in soilLayer.values())  # 40

# functional equivalent of generator comprehension
from operator import itemgetter
res = max(map(itemgetter(0), soilLayer.values()))  # 40

Another way, if you are happy using a 3rd party library, is to use numpy :另一种方法,如果您对使用 3rd 方库感到满意,则使用numpy

import numpy as np

res = np.array(list(soilLayer.values()))[:, 0].max()  # 40.0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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