def custom_sort(preprocess_func=lambda x: x):
"""
自定义排序方法
:param preprocess_func: 预处理函数,用于排序对象是元素内部的某一个元素时处理
比如:排序对象为 : ['('a', 3), ('b', 2)] 时 preproess_func = lambda x: x[1]
排序对象为:[2, 1, 3] 时: preprocess_func = lambda x: x 即默认,可不传
:return: 排序函数
"""
def sort_function(x, y):
"""
根据 preprocess_func 定制的排序函数
:param x:
:param y:
:return: x > y: 1, x < y: -1, x == y: 0
"""
# 排序元素预处理
x = preprocess_func(x)
y = preprocess_func(y)
"""
自定义的排序规则,返回值: x > y: 1, x < y: -1, x == y: 0
"""
pass
return sort_function
# 用法示例
# 把下列数据按每个元素中的第一个元素排列
data = [('12,34', 1), ('56,78', 1), ('3,34', 1), ('6,789', 1)]
# step 1, 编写自定义比较规则
def custom_sort(preprocess_func=lambda x: x):
"""
自定义排序方法
:param preprocess_func: 预处理函数,用于排序对象是元素内部的某一个元素时处理
比如:排序对象为 : ['('a', 3), ('b', 2)] 时 preproess_func = lambda x: x[1]
排序对象为:[2, 1, 3] 时: preprocess_func = lambda x: x 即默认,可不传
:return: 排序函数
"""
def sort_function(x, y):
"""
根据 preprocess_func 定制的排序函数
:param x:
:param y:
:return: x > y: 1, x < y: -1, x == y: 0
"""
# 排序元素预处理
x = preprocess_func(x)
y = preprocess_func(y)
"""
自定义的排序规则,返回值: x > y: 1, x < y: -1, x == y: 0
"""
x_codes = [int(num) for num in x.split(',')]
y_codes = [int(num) for num in y.split(',')]
for i in range(len(x_codes)):
# 如果比较 x 这一位时还没比出结果,而 y 已经没有这一位了,则说明前面一样,但 x 更长,x > y !
if i >= len(y_codes):
return 1
# 比较当前位,如果一样则比较下一位
if x_codes[i] == y_codes[i]:
continue
elif x_codes[i] > y_codes[i]:
return 1
elif x_codes[i] < y_codes[i]:
return -1
else:
print('compare error')
# 如果在上面的 x 循环中没有比较出大小,则说明 x == y 或者 y 还有一部分 x < y, 直接返回 y
if x_codes == y_codes:
return 0
return -1
pass
return sort_function
# step2 导入 cmp_to_key
from functools import cmp_to_key
# step3 排序
print(sorted(data, key=cmp_to_key(custom_sort(lambda x: x[0]))))