Pyhon列表排序(升序和降序)

一、sort()方法:
list.sort(cmp=None, key=None, reverse=False)
cmp -- 可選參數, 如果指定了該參數會使用該參數的方法進行排序。
key -- 主要是用來進行比較的元素,只有一個參數,具體的函數的參數就是取自於可迭代對象中,指定可迭代對象中的一個元素來進行排序。
reverse -- 排序規則,reverse = True 降序, reverse = False 升序(默認)。



#列表升序
list1=['python','java','c++','阿里','1','2','3']
list1.sort()
print(list1)
#列表降序
list1.sort(reverse=True)
print(list1)

"C:\Program Files\Python35\python.exe" C:/Users/wangli/PycharmProjects/Test/test/test01.py
['1', '2', '3', 'c++', 'java', 'python', '阿里']
['阿里', 'python', 'java', 'c++', '3', '2', '1']

Process finished with exit code 0


二、sorted()函數:
sorted(iterable, cmp=None, key=None, reverse=False)
iterable -- 可迭代對象。
cmp -- 比較的函數,這個具有兩個參數,參數的值都是從可迭代對象中取出,此函數必須遵守的規則爲,大於則返回1,小於則返回-1,等於則返回0。
key -- 主要是用來進行比較的元素,只有一個參數,具體的函數的參數就是取自於可迭代對象中,指定可迭代對象中的一個元素來進行排序。
reverse -- 排序規則,reverse = True 降序 , reverse = False 升序(默認)。

#列表升序
list2=[("python","java"),("c","c++"),("1","php")]
print(sorted(list2))
#列表降序
print(sorted(list2,reverse = True))


#通過key的值來進行數組/字典的升序
array = [{"age": 20, "name": "a"}, {"age": 25, "name": "b"}, {"age": 10, "name": "c"}]
array_data = sorted(array, key=lambda x: x["age"])
print(array_data)


#先按照成績降序排序,相同成績的按照名字升序排序:
dict_data = [{'name': 'alice', 'score': 38}, {'name': 'bob', 'score': 18}, {'name': 'darl', 'score': 28},
             {'name': 'christ', 'score': 28}]
dict_sorted = sorted(dict_data, key=lambda x: (-x['score'], x['name']))
print(dict_sorted)


"C:\Program Files\Python35\python.exe" C:/Users/wangli/PycharmProjects/Test/test/test01.py
[('1', 'php'), ('c', 'c++'), ('python', 'java')]
[('python', 'java'), ('c', 'c++'), ('1', 'php')]
[{'age': 10, 'name': 'c'}, {'age': 20, 'name': 'a'}, {'age': 25, 'name': 'b'}]
[{'name': 'alice', 'score': 38}, {'name': 'christ', 'score': 28}, {'name': 'darl', 'score': 28}, {'name': 'bob', 'score': 18}]

Process finished with exit code 0

三、sort ()與sorted()區別:
sort()是應用在list上的方法,sorted()可以對所有可迭代的對象進行排序操作。
list的sort()方法返回的是對已經存在的列表進行操作,無返回值,而內建函數sorted()方法返回的是一個新的list,而不是在原來的基礎上進行的操作。

四、冒泡排序

是最常見到的排序算法,也是很基礎的一種排序算法。它的實現思想是:相鄰的兩個元素進行比較,然後把較大的元素放到後面(正向排序),在一輪比較完後最大的元素就放在了最後一個位置,像魚兒在水中吐的氣泡在上升的過程中不斷變大

list3=["3","9","1","A","p"]
for i in range(len(list3)):
    for j in range(i+1,len(list3)):
        if list3[i]>list3[j]:
            list3[i],list3[j]=list3[j],list3[i]
print(list3)

"C:\Program Files\Python35\python.exe" C:/Users/wangli/PycharmProjects/Test/test/test01.py
['1', '3', '9', 'A', 'p']

Process finished with exit code 0

五、選擇排序
選擇排序的思路是:第一輪的時候,所有的元素都和第一個元素進行比較,如果比第一個元素大,就和第一個元素進行交換,在這輪比較完後,就找到了最小的元素;第二輪的時候所有的元素都和第二個元素進行比較找出第二個位置的元素,以此類推。

list4=["3","9","1","2","4"]
for i in range(len(list4)-1,0,-1):
    for j in range(i):
        if list4[j]>list4[i]:
            list4[j], list4[i] = list4[i], list4[j]
print(list4)


"C:\Program Files\Python35\python.exe" C:/Users/wangli/PycharmProjects/Test/test/test01.py
['1', '2', '3', '4', '9']

Process finished with exit code 0

 

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