gpt4 book ai didi

python - 有没有办法在列表中引用对象的两个属性?

转载 作者:行者123 更新时间:2023-11-30 22:48:30 24 4
gpt4 key购买 nike

我想知道谁是对象列表中较高的运动员(对象)。如果我想打印它,我尝试这样写:

print ("The greater height is",max(x.height for x in athletes_list),"meters.")

它显示了较高运动员的高度,但我不知道如何通过这种方式获取他的名字,将所有命令放在 print 的正文中。有什么办法可以做到这一点吗?

我知道通过创建这样的 for 是可能的:

for i in athletes_list:
if i.height==max(x.height for x in athletes_list):
print ("The taller athlete is",i.name,"with",i.height,"meters.")

是否可以仅在 print 正文中获取这两个信息?抱歉英语不好。

最佳答案

重读你的问题。答案仍然是肯定的。使用字符串的format方法:

print("The taller athlete is {0.name} with {0.height} meters.".format(max(athletes_list, key=lambda a: a.height)))

关于python - 有没有办法在列表中引用对象的两个属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40139814/

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