本文实例讲述了Python使用sort和class实现的多级排序功能。分享给大家供大家参考,具体如下:
# -*- coding:utf-8 -*-import randomclass 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.atemp = []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])# print print # 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]
[a: 7 b: 97 c: 24]
[a: 8 b: 32 c: 84]
[a: 8 b: 49 c: 90]
[a: 9 b: 13 c: 22]
[a: 9 b: 29 c: 99]
[a: 10 b: 52 c: 11]
[a: 11 b: 2 c: 62]
[a: 11 b: 20 c: 56]
[a: 11 b: 38 c: 17]
[a: 11 b: 72 c: 2]
[a: 12 b: 13 c: 48]
[a: 15 b: 39 c: 24]
[a: 15 b: 64 c: 84]
[a: 16 b: 31 c: 89]
[a: 16 b: 60 c: 15]
[a: 16 b: 68 c: 33]
[a: 17 b: 44 c: 97]
[a: 17 b: 82 c: 41]
[a: 17 b: 96 c: 4]
[a: 19 b: 47 c: 22]
[a: 19 b: 97 c: 91]
[a: 20 b: 35 c: 87]
[a: 20 b: 45 c: 71]
[a: 20 b: 58 c: 45]
[a: 21 b: 5 c: 29]
[a: 21 b: 12 c: 1]
[a: 21 b: 24 c: 84]
[a: 21 b: 27 c: 41]
[a: 21 b: 34 c: 4]
[a: 21 b: 44 c: 38]
[a: 21 b: 63 c: 60]
[a: 21 b: 88 c: 60]
[a: 22 b: 15 c: 39]
[a: 23 b: 6 c: 90]
[a: 23 b: 45 c: 36]
[a: 23 b: 95 c: 92]
[a: 24 b: 44 c: 48]
[a: 24 b: 79 c: 86]
[a: 25 b: 40 c: 24]
[a: 25 b: 80 c: 46]
[a: 25 b: 100 c: 40]
[a: 26 b: 34 c: 74]
[a: 26 b: 79 c: 23]
[a: 27 b: 6 c: 51]
[a: 27 b: 8 c: 8]
[a: 27 b: 28 c: 86]
[a: 27 b: 71 c: 48]
[a: 28 b: 5 c: 9]
[a: 29 b: 11 c: 91]
[a: 29 b: 42 c: 17]
[a: 29 b: 47 c: 21]
[a: 31 b: 80 c: 86]
[a: 32 b: 18 c: 24]
[a: 32 b: 30 c: 29]
[a: 32 b: 81 c: 55]
[a: 33 b: 33 c: 10]
[a: 33 b: 36 c: 83]
[a: 34 b: 11 c: 27]
[a: 34 b: 60 c: 52]
[a: 34 b: 62 c: 45]
[a: 34 b: 72 c: 37]
[a: 35 b: 81 c: 50]
[a: 35 b: 88 c: 3]
[a: 36 b: 11 c: 64]
[a: 36 b: 57 c: 93]
[a: 36 b: 92 c: 2]
[a: 38 b: 58 c: 83]
[a: 39 b: 39 c: 66]
[a: 39 b: 47 c: 15]
[a: 40 b: 13 c: 3]
[a: 40 b: 50 c: 66]
[a: 40 b: 99 c: 71]
新闻热点
疑难解答