Eduardo M Eduardo M - 1 month ago 5
Python Question

Is there a way to refer two attributes of an object in a list?

I want to know who is the taller athlete (object) in a list of objects. If I want to print it, I tried to write this:

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


It shows the height of the taller athlete, but I don't know how to get his name by this way, putting all commands in print's body. Is there any way to do this?

I know its possible by creating a for like this:

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.")


Is it possible to get both informations only in print's body?
Sorry for bad english.

Answer

Reread your question. The answer is still yes. Use the format method of strings:

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