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

标签 python python-3.x list dictionary

我想获得第一个值的最大值 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/

相关文章:

c++ - 如何编写程序重命名 mp4 文件以匹配 srt 文件的名称?

python - 并排排列 Wagtailstream 字段

python - 转置和扩展数据

python - 如何为每个句子(行)创建标记化单词(列)的数据框?

java - 在 Java 中将值附加到列表的元素

java - 使用hibernate获取列表形式的对象

python - 无法使用 scrapy 抓取结果列表上的数据

while循环中的Python套接字接收数据不会停止

css - PyQt5 TextEdit Widget 更改输入文本的字体颜色

python - 从 Pandas Dataframe 获取一个或多个列值作为列表