sorted函数可以对可迭代类型的容器内的数据进行排序
lst1 = (5,4,3,2,1)
lst2 = ('F','D','Y','e','a','v')#字符串类型的排序按照ASCII的大小进行比较
L1 = sorted(lst1)
L2 = sorted(lst2)
print(L1)
print(L2)
>>>[1, 2, 3, 4, 5]
['D', 'F', 'Y', 'a', 'e', 'v']
sorted(L,key=···) 其中key用来接收一个自定义的排序规则
lst1 = (5,4,3,-2,1)
lst2 = ('F','D','Y','e','a','v')#字符串类型的排序按照ASCII的大小进行比较
L1 = sorted(lst1)
L2 = sorted(lst2)
L3 = sorted(lst1,key=abs)
L4 = sorted(lst2,key=str.lower)
print(L1)
print(L2)
print(L3)
print(L4)
>>>[-2, 1, 3, 4, 5]
['D', 'F', 'Y', 'a', 'e', 'v']
[1, -2, 3, 4, 5]
['a', 'D', 'e', 'F', 'v', 'Y']
其中sorted函数是默认升序排序,当需要降序排序时,需要使用reverse = True
lst1 = (5,4,3,-2,1)
lst2 = ('F','D','Y','e','a','v')#字符串类型的排序按照ASCII的大小进行比较
L1 = sorted(lst1)
L2 = sorted(lst2)
L3 = sorted(lst1,key=abs)
L4 = sorted(lst2,key=str.lower)
L5 = sorted(lst1,reverse=True)
print(L1)
print(L2)
print(L3)
print(L4)
print(L5)
>>>[-2, 1, 3, 4, 5]
['D', 'F', 'Y', 'a', 'e', 'v']
[1, -2, 3, 4, 5]
['a', 'D', 'e', 'F', 'v', 'Y']
[5, 4, 3, 1, -2]
operator模块提供的itemgetter函数用于获取对象的哪些维的数据
from operator import itemgetter
L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]
#按名字排序
L2=sorted(L,key=itemgetter(0))
#按成绩排序
L3=sorted(L,key=itemgetter(1))
print("按名字排序: ")
print(L2)
print("按成绩排序: ")
print(L3)
>>>按名字排序:
[('Adam', 92), ('Bart', 66), ('Bob', 75), ('Lisa', 88)]
按成绩排序:
[('Bart', 66), ('Bob', 75), ('Lisa', 88), ('Adam', 92)]
如果在输出列表时不想输出中括号,引号和逗号。可以在输出时在变量前加一个’*'即可
lst1 = (5,4,3,-2,1)
lst2 = ('F','D','Y','e','a','v')#字符串类型的排序按照ASCII的大小进行比较
L1 = sorted(lst1)
L2 = sorted(lst2)
L3 = sorted(lst1,key=abs)
L4 = sorted(lst2,key=str.lower)
L5 = sorted(lst1,reverse=True)
print(*L1)
print(*L2)
print(*L3)
print(*L4)
print(*L5)
>>>-2 1 3 4 5
D F Y a e v
1 -2 3 4 5
a D e F v Y
5 4 3 1 -2
参考网址:https://blog.csdn.net/chaojishuike/article/details/124049419