python attrgetter使用

from operator import attrgetter

class User:
    def __init__(self,  card):
        self.card = card

    def __repr__(self):
        return str(self.card)

a = [User(1), User(4), User(3)]

a1 = list(sorted(a, key=attrgetter('card')))
print(a1)
a2 = list(sorted(a, key=lambda x: x.card))
print(a2)

输出

[1, 3, 4]
[1, 3, 4]

你可能感兴趣的:(python)