1 python 常用函数
1.1 排序函数
原地排序 nums.sort()
不改变原列表有返回值 new = sorted(nums)
import functools
# 一维数组排序
nums = [2, 1, 3, 4, 5]
def compare_udf(x, y):
# x - y 升序
# y - x 降序
return x - y
# # python2
nums.sort(cmp=compare_udf)
# # python3
nums.sort(key=functools.cmp_to_key(compare_udf))
print(nums)
nums = [(264.0, 8, 0), (199.0, 10, 1), (230.0, 10, 2), (199.0, 9, 3)]
# 基础排序 按照一维升序排列,按照二维降序排列
new = sorted(nums, key=lambda x: (x[0], -x[1]))
print(new)
# 自定义排序
import functools
def comp(x, y):
if x[0] != y[0]:
return x[0] - y[0]
else:
return y[1] - x[1]
new = sorted(nums, key=functools.cmp_to_key(comp))
print(new)
标签:compare,nums,functools,key,new,排序,leetcode
From: https://www.cnblogs.com/liuyechang/p/17445299.html