摘要:在一些场景中,需要重新对已有的数据排序,可能所给出的数据类型或者数据数量较多,需要给定排序规则。
import functools
def by_score(t1,t2):
if t1[0]>t2[0]:
return 1
elif t1[0]t2[1]:
return 1
elif t1[1]==t2[1]:
return 0
else:
return -1
def md():
datas=[['Bob', 99,1],['Bart', 66,2],['Bob', 29,3], ['Adam', 92,4],['Bob', 29,5], ['Adam', 90,6], ['Bart', 66,7], ['Lisa', 88,8]]
datas.sort(key=functools.cmp_to_key(by_score)) # 稳定排序
print(datas)
#[['Adam', 90, 6], ['Adam', 92, 4], ['Bart', 66, 2], ['Bart', 66, 7], ['Bob', 29, 3], ['Bob', 29, 5], ['Bob', 99, 1], ['Lisa', 88, 8]]
class Pos:
def __init__(self,x,y):
self.x=x
self.y=y
def cmp(a, b):
return a.x - b.x if a.x != b.x else a.y - b.y # x y均按照从小到大的顺序
def mySorted():
test_list = [Pos(5, 1), Pos(2, 5), Pos(2, 4)]
# test_list.sort(key=functools.cmp_to_key(lambda a,b: a.x-b.x if a.x != b.x else a.y-b.y))
test_list.sort(key=functools.cmp_to_key(cmp))
# sorted(test_list, key=functools.cmp_to_key(cmp)) # 亲测此方法不能成功排序
for number in test_list:
print(number.x,' ',number.y)