python-sort()與sorted()區別與聯繫

sort()應該是list.sort()是一個僅用在list結構中的函數,sorted()是一個內置函數,可以對任何可迭代的對象進行排序操作,並且不會改變原結構,產生新排序後的結果。

list.sort()

list.sort(key=(比較的關鍵字),reverse=False(升序,默認) or True (降序) )

sort()函數,從列表中拿出每個元素,按照給出的key來進行比較,最後返回排序結果。 

例子1:按照單詞長度排序

word = ['time','me','aganist']
word.sort(key = lambda x:len(x)) 
#從列表中拿出一個單詞x,返回他的長度

# word.sort() ##最原始的就是按照單詞順序排序
 
print(word) #-> ['me', 'time', 'aganist']

例子2:按照數字平方大小排序

num = [-1,0,1,4,-9,8] 
num.sort(key = lambda x:x**2,reverse = True) #降序

print(num) #->[-9, 8, 4, -1, 1, 0]

sorted()

sorted(iterable(可迭代對象),key,reverse )

sorted()函數,從可迭代對象中拿出每個元素,按照給出的key來進行比較,最後返回排序結果。

例子3(列表使用):

word = ['time','me','aganist']
word_1 = sorted(word,key = lambda x:len(x))
print(word_1) #與例1相同結果

例子4,(構造好的詞頻,統計前頻率最高的幾個單詞):

dic = {'mother':1,'sun':3,'uncle':2,'sister':9}

dic = sorted(dic.items(),key = lambda x:x[1],reverse =True)

### 注意,必須是dic.items(),dic是可迭代對象類型,但dic默認可迭代對象是key
print(dic[:3]) #前三個單詞

例子5,列表中不僅是int類型,還有char類型,不可比較時,利用functools.cmp_to_key()。Python2中的sorted 可以指定cmp關鍵字參數,就是當遇到需要自定義比較操作的數據可以通過 cmp=compare 來實現,不需要像Python3中還需要導入functools.cmp_to_key實現。

import functools

nums = [3, 1.5, 2.5, '6', '2.5']
def compare(x1, x2):
    if isinstance(x1, str):
        x1 = float(x1)
    if isinstance(x2, str):
        x2 = float(x2)

    return x1 - x2

>>>sorted(nums, key=functools.cmp_to_key(compare))
[1.5, 2.5, '2.5', 3, '6']

例子同樣來自上面的鏈接,說明一下爲什麼比較結果是這樣的。functools.cmp_to_key(),接受兩個參數也就是從L中按照一定的順序拿出兩個位置的內容,如3和‘6’。然後帶入到compare(自定義)函數中。用定義的方法比較他們,最後返回一個數字。如果是正數,代表大於,負數是小於,0是等於。如果是3和'6'帶進去,那麼輸出的意思就是3大於‘6’。注意是string類型的6。

補一個題:面試題45. 把數組排成最小的數  來自題解:@Krahets

題目是要按照題中所述,總結比較規則,然後按照規則排序。

class Solution:
    def minNumber(self, nums: List[int]) -> str:
        def sort_rule(x, y): # 比較x,y大小
            a, b = x + y, y + x
            if a > b: return 1 # x+y >y+x -----> x>y
            elif a < b: return -1  ## 小於
            else: return 0  ##等於
        
        strs = [str(num) for num in nums]
        strs.sort(key = functools.cmp_to_key(sort_rule)) ##比較規則,按照定義的比較規則去排序
        return ''.join(strs)

補充一點:sort()函數的時間複雜度是O(NlogN),與內部機制(Timsort)有關,詳細介紹點鏈接

參考:

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

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

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