Python基礎之sorted()函數用法

1、簡單的排序

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']

2、進階使用

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']

3、選擇升序還是降序排列方式

其中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]

4、多級排序

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章