如何修改Python代码以输出最高海拔山峰的名称与高度?
Hey, I see your current code only outputs the highest elevation number, but you want to display both the mountain name and its height in the format "Highest is: Mount Everest 8850". Let's fix that easily!
The Problem with Your Current Code
Your existing max() call only passes individual height values, so it just returns the largest number instead of the full mountain object that holds both name and height info.
The Modified Solution
Instead of feeding separate height values to max(), we'll pass a list of all your Mountain instances, and tell max() to use the height attribute as the comparison key. This way, it returns the actual mountain object, and we can access both its name and height properties to build your desired output.
class Mountain: def __init__(self, name, height): self.name = name self.height = height # Create all mountain instances mountain_01 = Mountain("Mount Everest", 8850) mountain_02 = Mountain("Mount Kazbek", 5033) mountain_03 = Mountain("Vinson Massif", 4892) mountain_04 = Mountain("Kilimanjaro", 5895) # Get the mountain object with the highest height highest_mountain = max([mountain_01, mountain_02, mountain_03, mountain_04], key=lambda x: x.height) # Print the desired format print(f"Highest is: {highest_mountain.name} {highest_mountain.height}")
What Changed?
- We wrapped all mountain instances into a list:
[mountain_01, mountain_02, mountain_03, mountain_04] - Added the
keyparameter tomax():key=lambda x: x.heighttells the function to compare each mountain by itsheightattribute - Now
highest_mountainis a fullMountainobject, so we can accesshighest_mountain.nameandhighest_mountain.heightto output exactly the format you want
内容的提问来源于stack exchange,提问作者Sandro Kakoishvili

