PYTHON-排序-sort與sorted區別及應用

list.sort( key=None, reverse=False)
#list就是咱們須要排序的列表;
#key:具體的函數的參數就是取自於可迭代對象中,指定可迭代對象中的一個元素來進行排序。
#reverse :True 降序,False 升序(默認)
def takeSecond(elem):
    print(elem[1])
    return elem[1]
 
# 列表
random = [(2, 2), (3, 4), (4, 1), (1, 3)]
 
# 指定第二個元素排序
random.sort(key=takeSecond)
 
# 輸出類別
print ('排序列表:', random)
#output
2 4 1 3 排序列表: [(4, 1), (2, 2), (1, 3), (3, 4)] #就是按照列表裏邊的元組的第二個元素進行排序

 

sorted 與 sort的區別:html

#sort是在list上的方法,而sorted能夠應用在任何可迭代對象;
#sort是在原有列表上操做,sorted是返回一個新的列表
#sorted(iterable, key=None, reverse=False)  
>>> a = [5,2,3,1,4]
>>> a.sort()
>>> a
[1, 2, 3, 4, 5] #在原有列表上操做
>>> a.sorted()
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    a.sorted()
AttributeError: 'list' object has no attribute 'sorted'
>>> sorted([5,2,3,1,4])
[1, 2, 3, 4, 5]#產生一個新列表
>>> 

 

參考網址:python

https://www.runoob.com/python3/python3-func-sorted.htmlshell

https://www.runoob.com/python3/python3-att-list-sort.htmldom

相關文章
相關標籤/搜索