2022年 11月 7日

【Python】自定义排序函数

目录

自定义排序函数

实现忽略大小写排序的算法

剑指 Offer 45. 把数组排成最小的数


python 自定义排序函数

自定义排序函数

Python内置的 sorted()函数可对list进行排序:

  1. >>>sorted([36, 5, 12, 9, 21])
  2. [5, 9, 12, 21, 36]

但 sorted()也是一个高阶函数,它可以接收一个比较函数来实现自定义排序,

比较函数的定义是,传入两个待比较的元素 x, y,如果 x 应该排在 y 的前面,返回 -1,如果 x 应该排在 y 的后面,返回 1。如果 x 和 y 相等,返回 0。

因此,如果我们要实现倒序排序,只需要编写一个reversed_cmp函数:

  1. def reversed_cmp(x, y):
  2.     if x > y:
  3.         return -1
  4.     if x < y:
  5.         return 1
  6.     return 0

这样,调用 sorted() 并传入 reversed_cmp 就可以实现倒序排序:

  1. >>> sorted([36, 5, 12, 9, 21], reversed_cmp)
  2. [36, 21, 12, 9, 5]

sorted()也可以对字符串进行排序,字符串默认按照ASCII大小来比较:

  1. >>> sorted(['bob', 'about', 'Zoo', 'Credit'])
  2. ['Credit', 'Zoo', 'about', 'bob']
  3. 'Zoo'排在'about'之前是因为'Z'的ASCII码比'a'

实现忽略大小写排序的算法

对字符串排序时,有时候忽略大小写排序更符合习惯。请利用sorted()高阶函数,实现忽略大小写排序的算法。

输入:[‘bob’, ‘about’, ‘Zoo’, ‘Credit’]
输出:[‘about’, ‘bob’, ‘Credit’, ‘Zoo’]

  1. def cmp_ignore_case(s1, s2):
  2.     t1=s1.lower();
  3.     t2=s2.lower();
  4.     if(t1>t2):
  5.         return 1
  6.     if(t1==t2):
  7.         return 0
  8.     return -1
  9. print sorted(['bob', 'about', 'Zoo', 'Credit'], cmp_ignore_case)

剑指 Offer 45. 把数组排成最小的数

输入一个非负整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。

输入: [3,30,34,5,9]
输出: "3033459"
  1. class Solution:
  2. """
  3. 若拼接字符串 x+y>y+x ,则 x “大于” y ;
  4. 反之,若 x+y<y+x ,则 x “小于” y ;
  5. """
  6. def sort_rule(self,x,y):
  7. a, b = x+y, y+x
  8. if a>b: return 1
  9. elif a<b:return -1
  10. else:
  11. return 0
  12. def minNumber(self, nums: List[int]) -> str:
  13. strs = [str(num) for num in nums]
  14. strs.sort(key=functools.cmp_to_key(self.sort_rule))
  15. return ''.join(strs)

https://leetcode-cn.com/problems/ba-shu-zu-pai-cheng-zui-xiao-de-shu-lcof/solution/mian-shi-ti-45-ba-shu-zu-pai-cheng-zui-xiao-de-s-4/