python实现结构体排序

python默认提供的列表sort方法,仅支持列表的元素排序。若想实现结构提排序,可参考下面方法:

1、使用 lambda 表达式

 1 class struct:
 2     def __init__ (self):
 3         self.a = 0
 4         self.b = 'a'
 5 
 6 struct_list = []
 7 char_list = ['a', 'b', 'c']
 8 
 9 for i in range(3):
10     tem = struct()
11     tem.a = 3 - i
12     tem.b = char_list[i]
13     struct_list.append(tem)
14 
15 from functools import cmp_to_key
16 
17 # def cmp(a, b) :
18 #     if a.a < b.a :
19 #         return -1 # 不交换
20 #     else:
21 #         return 1 # 交换
22 
23 def cmp(a, b) :
24     if a.a < b.a :
25         return 1 # 交换
26     else:
27         return -1 # 不交换
28 
29 
30 # struct_list.sort(key=cmp_to_key(cmp))
31 # struct_list.sort(key=lambda x:x.a, reverse=True)
32 struct_list.sort(key=lambda x:x.a, reverse=False)
33 
34 for i in range(3):
35     print(str(i) + ':' + str(struct_list[i].a) + struct_list[i].b)

如上代码所示,根据结构体的域段a来排序,默认reverse为False,表示升序,

2、使用cmp方法,

如上例行30所示,

posted @ 2023-09-12 21:16  King--jin  阅读(260)  评论(0)    收藏  举报