python的sort是什么功能_Python使用sort和class实现的多级排序功能示例

本文实例讲述了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])

#

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]</

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值