sorted()
sorted函数用来对可迭代对象(比如列表)进行排序。
sorted(iterable, key=…,reverse=ture/false),比如 :
1、对一维列表进行排序(最简单的、不用key函数):
a = [1, 5, 2, 9, 4]
b = sorted(a)#默认按ASCII排序
print(a)
[1, 5, 2, 9, 4]
**、、、、、、、、、、、 (复杂点的、使用key函数):
a = [1, 5, 2, 9, 4]
b = sorted(a, key = lambda x:abs(x-4))
print(b)
[4, 5, 2, 1, 9] #对a中元素按照函数|x-4|从小到大的顺序排序
解释:其中 lambda是匿名函数,lambda x:abs(x-4)就是你在冒号后定义列表中的元素x按照|x-4|从小到大的顺序排序
、、、、、、、、、、、、 (然后用reverse)**
a = [1, 2, 5, 2, 3]
b = sorted(a, reverse = False)#升序
print(b)
[1, 2, 2, 3, 5]c = sorted(a, reverse = True)#倒序
print(c )
[5, 3, 2, 2, 1]
2、再复杂点 ,,用sorted对列表中内含元组进行排序
a = [(‘b’, 2), (‘t’, 7), (‘h’, 8)]
b = sorted(a, key = lambda x:(x[0], x[1]))
print(b) #x[0]表示元组中第一个元素;x[2]表示元组中的第二个元素 。 所以lambda定义的函数为以元组中的第一个元素从小到大排序,元素相同的按第二个元素排(可以用-x[0]表示倒序:从大到小)
[(‘b’, 2), (‘h’, 8), (‘t’, 7)]
3、对字典排序,先将字典可迭代化:用dict.items()
dict1 = {‘height’:170, ‘weight’:60, ‘iq’:180}
b = sorted(dict1.items(), key = lambda x:len(x[0])) #按照字典中键的字符串长度排序
print(b)
[(‘iq’, 180), (‘height’, 170), (‘weight’, 60)]c = sorted(dict1.items(), key = lambda x:-x[1]) #按照字典中的值从大到小排
print©
[(‘iq’, 180), (‘height’, 170), (‘weight’, 60)]