我想知道对象列表中谁是较高的运动员(对象)。如果我想打印它,我试着写这个:
print ("The greater height is",max(x.height for x in athletes_list),"meters.")
它显示了较高运动员的身高,但我不知道如何通过这种方式获得他的名字,将所有命令都印在身体上。有没有办法做到这一点?
我知道可能通过创建这样的:
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.")
是否可以仅在印刷品中获取这两种信息? 抱歉英文不好。
答案 0 :(得分:2)
重读你的问题。答案仍然是肯定的。使用format
字符串方法:
print("The taller athlete is {0.name} with {0.height} meters.".format(max(athletes_list, key=lambda a: a.height)))
答案 1 :(得分:1)
在两个值上使用max
(首先是高度):
from future_builtins import map # Only on Py2, to get generator based map
from operator import attrgetter
# Ties on height will go to first name alphabetically
maxheight, name = max(map(attrgetter('height', 'name'), athletes))
print("The taller athlete is", name, "with", maxheight, "meters.")
或者因此关系是通过出现顺序来解决的,而不是名称:
maxheight, name = attrgetter('height', 'name')(max(athletes, key=attrgetter('height')))