Python3自定义sorted()中key排序函数

Introduction

python3 sorted取消了对cmp的支持。
python3 帮助文档:
sorted(iterable, key=None, reverse=False)

  • reverse是一个布尔值。如果设置为True,列表元素将被倒序排列,默认为False
  • key接受一个函数,这个函数只接受一个元素,默认为None

举个栗子

对每个元素中包含多个项,定义不同的排序规则

在这里插入图片描述

一个字符串排序,排序规则:小写<大写<奇数<偶数

#元组内(e1, e2, e3)的优先级排列为: e1 > e2 > e3
s = 'asdf234GDSdsf23'
res = sorted(s, key=lambda x: (x.isdigit(),x.isdigit() and int(x) % 2 == 0,x.isupper(),x)
print(res)
#input: 'asdf234GDSdsf23'
#output: ['a', 'd', 'd', 'f', 'f', 's', 's', 'D', 'G', 'S', '3', '3', '2', '2', '4']

  • x.isdigit()的作用是把数字放在后边(True),字母放在前面(False).
  • x.isdigit() and int(x) % 2 == 0的作用是保证数字中奇数在前(False),偶数在后(True)。
  • x.isupper()的作用是在前面基础上,保证字母小写(False)在前大写在后(True).
  • 最后的x表示在前面基础上,对所有类别数字或字母排序。

Reference

https://blog.csdn.net/jason_cuijiahui/article/details/72771596

猜你喜欢

转载自blog.csdn.net/m0_38024592/article/details/109582090