首页 > 代码库 > python之attrgetter函数对对象排序

python之attrgetter函数对对象排序

 1 # 使用attrgetter函数对对象排序
 3 # attrgetter处理对象,itemgetter处理序列
 4 
 5 from operator import attrgetter
 6 
 7 
 8 class user():
 9     def __init__(self, name, age):
10         self.name = name
11         self.age = age
12 
13     def __repr__(self):
14         ‘‘‘定义该对象需要输出时的字符串格式‘‘‘
15         return self.name + ":" + str(self.age)
16 
17 
18 users = [
19     user("Mike", 28),
20     user("Lily", 25),
21     user("Tom", 27),
22     user("Ben", 23)
23 ]
24 
25 print(排序前:)
26 for user in users:
27     print(user)
28 
29 print(- * 20)
30 print(排序后:)
31 
32 for u in sorted(users, key=attrgetter("name")):
33     ‘‘‘根据对象名称排序-key(u)‘‘‘
34     print(u)
35 
36 for u in sorted(users, key=attrgetter("name", "age")):
37     ‘‘‘多键值排序‘‘‘
38     print(u)

运行结果:

 1 排序前:
 2 Mike:28
 3 Lily:25
 4 Tom:27
 5 Ben:23
 6 --------------------
 7 排序后:
 8 Ben:23
 9 Lily:25
10 Mike:28
11 Tom:27

 

python之attrgetter函数对对象排序