gpt4 book ai didi

python - 打印最大值和数据

转载 作者:太空宇宙 更新时间:2023-11-03 20:47:13 27 4
gpt4 key购买 nike

我想获取具有最高值(value)的数据。

class Mountain:

def __init__(self, name, height):
self.name = name
self.height = height

mountain_01 = Mountain("Mount Everest", 8850)
mountain_02 = Mountain("Mount Kazbek", 5033)
mountain_03 = Mountain("Vinson Massif", 4892)
mountain_04 = Mountain("Kilimanjaro", 5895)

highest_mountain = max(mountain_01.height, mountain_02.height,
mountain_03.height, mountain_04.height)
print(f"Highest is : {highest_mountain}")

我期望输出为“最高的是:珠穆朗玛峰 8850”

最佳答案

您可以首先捕获列表中的所有山脉,然后计算 max在该列表上,使用键作为山的高度

#List of mountains
mountains = [mountain_01, mountain_02, mountain_03, mountain_04]

#Get highest mountain based on height of mountain
highest_mountain = max(mountains, key=lambda mountain:mountain.height)

print(highest_mountain.name)
print(highest_mountain.height)

输出将是

Mount Everest
8850

关于python - 打印最大值和数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56508956/

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