我想获得第一个值的最大值 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 ) )
最佳答案
原生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
如果您喜欢使用第三方库,另一种方法是使用 numpy
:
import numpy as np
res = np.array(list(soilLayer.values()))[:, 0].max() # 40.0
关于python - 返回在字典中的键上循环的第一个值条目的最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49772143/