為什麼列表.sort() 在 Python 中沒有返回已排序列表?


示例


在本示例中,讓我們先了解 list.sort() 的用法,然後再繼續。這裡,我們建立了一個列表,並使用 sort() 方法按升序對其進行排序 −


# Creating a List myList = ["Jacob", "Harry", "Mark", "Anthony"] # Displaying the List print("List = ",myList) # Sort the Lists in Ascending Order myList.sort() # Display the sorted List print("Sort (Ascending Order) = ",myList)

輸出


List =  ['Jacob', 'Harry', 'Mark', 'Anthony']
Sort (Ascending Order) =  ['Anthony', 'Harry', 'Jacob', 'Mark']

當效能更為重要時,僅為列表建立副本進行排序將不被認為是一種好的方式,而且是浪費。因此,list.sort() 按原樣對列表進行排序。此方法不會返回已排序列表。這樣,當你需要已排序副本但又需要保留未排序版本時,就不會被誤導而意外地覆蓋列表。


相反,使用內建的 sorted() 函式返回一個新列表。此函式從提供的可迭代項中建立新列表,對其進行排序並返回它。


使用 sorted() 根據值對字典列表進行排序


示例


我們現在已使用 sorted() 方法對字典列表進行排序。


# List of dictionaries d = [ {"name" : "Sam", "marks" : 98}, {"name" : "Tom", "marks" : 93}, {"name" : "Jacob", "marks" : 97} ] # Display the Dictionary print("Dictionary = \n",d) # Sorting using values with the lambda function print("Sorted = \n",sorted(d, key = lambda item: item['marks']))

輸出


('Dictionary = \n', [{'name': 'Sam', 'marks': 98}, {'name': 'Tom', 'marks': 93}, {'name': 'Jacob', 'marks': 97}])
('Sorted = \n', [{'name': 'Tom', 'marks': 93}, {'name': 'Jacob', 'marks': 97}, {'name': 'Sam', 'marks': 98}])

更新於: 2022 年 9 月 20 日


425 次瀏覽


開啟你的職業

完成本課程以獲得認證

開始
廣告