python-排序

Created at 2020-12-12 Updated at 2021-12-12 Category python Tag python

sorted(iterable[, cmp[, key[, reverse]]])
  • cmp:自定义排序,cmp=lambda x,y: cmp(x.lower(), y.lower())
  • key:要排序的key
  • reverse:默认正序,设置为 Flase 为倒序

根据某个 key 排序

# dict
kids = [
    {'name': 'xiaoming', 'score': 99, 'age': 12},
    {'name': 'xiaohong', 'score': 75, 'age': 13},
    {'name': 'xiaowang', 'score': 88, 'age': 15}
]
sorted(kids, key=lambda x: x['score'])

# tuple
students = [('john', 'A', 15), ('jane', 'B', 12), ('dave','B', 10)]
sorted(students,key=lambda x: x[2]) #按照年龄来排序

多关键字排序

先根据 key1 排,再根据 key2 排

sorted(dict, key = lambda x: x[key1], x[key2])

特殊排序规则

默认sorted([True, False])==[False, True] (False=0 < True=1)

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

#元组内(e1, e2, e3)的优先级排列为: e1 > e2 > e3
sorted(s, key=lambda x: (x.isdigit(),x.isdigit() and int(x) % 2 == 0,x.isupper(),x)

#input: 'asdf234GDSdsf23'
#output: ['a', 'd', 'd', 'f', 'f', 's', 's', 'D', 'G', 'S', '3', '3', '2', '2', '4']
  1. x.isdigit()的作用是把数字放在后边(True),字母放在前面(False).
  2. x.isdigit() and int(x) % 2 == 0的作用是保证数字中奇数在前(False),偶数在后(True)。
  3. x.isupper()的作用是在前面基础上,保证字母小写(False)在前大写在后(True).
  4. 最后的x表示在前面基础上,对所有类别数字或字母排序。
Site by Cellophane using Hexo & Random

Hide