本文采用版本python3.5
列表的排序方法sort()
list.sort(key=None, reverse=False)
- key – 主要是用来进行比较的元素,只有一个参数,具体的函数的参数就是取自于可迭代对象中,指定可迭代对象中的一个元素来进行排序。
- reverse – 排序规则,reverse = True 降序, reverse = False 升序(默认)
>>> l=[1,5,9,7,8]
>>> l.sort()
>>> l
[1, 5, 7, 8, 9]
>>> l.sort(reverse = True)
>>> l
[9, 8, 7, 5, 1]
>>>
key指定一个函数
# 按照列表中元组的字母大小进行排序
>>> l=[(2, 'b'), (3, 'd'), (4, 'a'), (1, 'c')]
>>> l.sort(key=lambda t:t[1])
>>> l
[(4, 'a'), (2, 'b'), (1, 'c'), (3, 'd')]
>>>
内置排序函数sorted()
对可迭代的序列排序生成新的列表([ ])
sorted(Iterable,key=None, reverse=False)
- Iterable – 可迭代的序列(字符串、列表、元组)
- key – 主要是用来进行比较的元素,可以指定多个参数
- reverse – 排序规则,reverse = True 降序, reverse = False 升序(默认)
字符串
>>> ss = 'askjihvub'
>>> ''.join(sorted(ss))
'abhijksuv'
# 数字在字母前面,大写在小写前面(ascii码的大小)
>>> ss = 'askjihvub159AEB'
>>> ''.join(sorted(ss))
'159ABEabhijksuv'
元组
>>> tt = (1,8,4,9,7)
>>>> tuple(sorted(tt))
(1, 4, 7, 8, 9)
列表
列表元素类型必须相同才能排序
>>> l=['a','f','d','b',1,8,6]
>>> sorted(l)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: '<' not supported between instances of 'int' and 'str'
>>> l=['a','f','d','b']
>>> sorted(l)
['a', 'b', 'd', 'f']
借助operator模块的itemgetter
operator模块提供的itemgetter函数用于获取对象的哪些维的数据,参数为一些序号
要注意,operator.itemgetter函数获取的不是值,而是定义了一个函数,通过该函数作用到对象上才能获取值
# 按年龄为主要关键字,名字为次要关键字倒序排序: students = [[3,'Jack',12],[2,'Rose',13],[1,'Tom',10],[5,'Sam',12],[4,'Joy',8]]
>>> students = [[3,'Jack',12],[2,'Rose',13],[1,'Tom',10],[5,'Sam',12],[4,'Joy',8]]
>>> sorted(students, key=itemgetter(2,1), reverse=True) # 2,1是下标,分别表示年龄与名字
[[2, 'Rose', 13], [5, 'Sam', 12], [3, 'Jack', 12], [1, 'Tom',10], [4, 'Joy', 8]]
排序面试题
- 列表嵌套列表排序,年龄数字相同怎么办?
list_d = [['qw',18],['sa',10],['fgd',18],['nh',45],['yu',23]]
res = sorted(list_d,key=lambda x:(x[1],x[0]))
print('当年龄相同时添加另一个参数按照字母名称排序,结果为:',res)
# 当年龄相同时添加另一个参数按照字母名称排序,结果为: [['sa', 10], ['fgd', 18], ['qw', 18], ['yu', 23], ['nh', 45]]
- 根据键对字典排序
- 方法一:zip函数
dict_1 = {"name":"yx","sex":"man","city":"cd"}
#将字典转列表嵌套元组
foo = zip(dict_1.keys(),dict_1.values()) #得到可迭代对象
foo = list(foo)
res = sorted(foo,key=lambda x:x[0]) # 字典嵌套元组排序
print('排序结果为:',res) # [('city', 'cd'), ('name', 'yx'), ('sex', 'man')]
#排序完成后构建新的字典(字典生成式,也可用dict(res)
new_dic = {i[0]:i[1] for i in res}
- 方法二:使用字典items方法
dict_1 = {"name":"yx","sex":"man","city":"cd"}
#字典转成列表嵌套元组
res = sorted(dict_1.items(), key=lambda x:x[0])
print('排序结果为:',res) # [('city', 'cd'), ('name', 'yx'), ('sex', 'man')]
#构建新的字典
new_dic = dict(res)
- 使用lambda函数对list排序foo = [-5,8,0,4,9,-4,-20,-2,8,2,-4],输出结果为
[0,2,4,8,8,9,-2,-4,-4,-5,-20],正数从小到大,负数从大到小
# 要点:x<0 将列表正数放前面负数放后面;abs(x) 再按绝对值大小排序
foo = [-5,8,0,4,9,-4,-20,-2,8,2,-4]
# 1.先按照绝对值大小进行排序获得新列表,再按照正数在前负数在后排序
sorted(sorted(foo,key=lambda x:abs(x)),key=lambda x:x<0) # [0,2,4,8,8,9,-2,-4,-4,-5,-20]
# sorted(sorted(foo,key=lambda x:abs(x)),key=lambda x:x>=0) # [-2,-4,-4,-5,-20,0,2,4,8,8,9]
# 2.传两个条件,x<0和abs(x);sorted() 中key的排序规则可以有多个
sorted(foo,key=lambda x:(x<0, abs(x))) #
# [0,2,4,8,8,9,-2,-4,-4,-5,-20]