本文实例讲述了Python使用sort和class实现的多级排序功能。分享给大家供大家参考,具体如下: # -*- coding:utf-8 -*-
import random
class Temp:
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def __str__(self):
return ( ('[a: %d b: %d c: %d]' % (self.a, self.b, self.c)))
def cmp1(temp1, temp2):
if (temp1.a > temp2.a):
return 1;
elif(temp1.a == temp2.a):
if (temp1.b>temp2.b):
return 1;
elif(temp1.b == temp2.b):
return 0;
else:
return -1;
else:
return -1;
def cmp2(temp1):
return temp1.a
temp = []
for i in range(200):
a = random.randint(1, 100)
b = random.randint(1, 100)
c = random.randint(1, 100)
temp.append(Temp(a,b,c))
# for i in range(10):
# print(temp[i])
#
# for i in sorted(temp,cmp = cmp1):
# print(temp[i])
temp.sort(cmp1)
for i in range(200):
print(temp[i])
运行结果:
[a: 1 b: 61 c: 91]
[a: 1 b: 62 c: 4]
[a: 1 b: 66 c: 6]
[a: 1 b: 73 c: 8]
[a: 2 b: 24 c: 100]
[a: 2 b: 26 c: 26]
[a: 2 b: 52 c: 90]
[a: 4 b: 69 c: 36]
[a: 4 b: 100 c: 66]
[a: 7 b: 59 c: 10]</