python 排序自定义对象

2022-01-10 08:43:47 浏览数 (1)

class User: def init(self, user_id): self.user_id = user_id

代码语言:javascript复制
def __repr__(self):
    return 'User({})'.format(self.user_id)

def sort_notcompare(): users = [User(23), User(3), User(99)] print(users) print(sorted(users, key=lambda u: u.user_id))

或者:operator.attrgetter

from operator import attrgetter sorted(users, key=attrgetter('user_id')) [User(3), User(23), User(99)]

0 人点赞