gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 02:28:35 25 4
gpt4 key购买 nike

我想获得第一个值 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 ) )

最佳答案

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

另一种方法,如果您喜欢使用第 3 方库,那就是使用 numpy:

import numpy as np

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

关于python - 返回循环字典中键的第一个值条目的最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49772143/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com