简体   繁体   中英

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

    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. Then, you can all the max on result.

from operator import itemgetter

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

There are a few solutions in native 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 :

import numpy as np

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

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