Используя getattr , это легко превратить в однострочник.
Код (Python 3.5)
from pprint import pprint
class Student(object):
def __init__(self, age, height, weight, iq):
self.age = age
self.height = height
self.weight = weight
self.iq = iq
def __repr__(self):
return str({'age': self.age, 'height': self.height, 'weight': self.weight, 'iq': self.iq})
def top(objects, attr, num=5):
return sorted(objects, key=lambda x: getattr(x, attr), reverse=True)[:num]
students = [
Student(age=21, height=127, weight=168, iq=120),
Student(age=24, height=120, weight=120, iq=50),
Student(age=19, height=110, weight=400, iq=90),
Student(age=30, height=190, weight=30, iq=92),
Student(age=31, height=180, weight=168, iq=77),
Student(age=42, height=169, weight=168, iq=98)
]
pprint(top(students, 'iq'))
Результаты
[{'age': 21, 'iq': 120, 'weight': 168, 'height': 127},
{'age': 42, 'iq': 98, 'weight': 168, 'height': 169},
{'age': 30, 'iq': 92, 'weight': 30, 'height': 190},
{'age': 19, 'iq': 90, 'weight': 400, 'height': 110},
{'age': 31, 'iq': 77, 'weight': 168, 'height': 180}]