一、Python List排序的基礎知識
Python的內置函數sorted()可以對列表進行排序。使用方法為:sorted(list)。其中,list是要排序的列表,sorted()函數將返回排序後的列表。這個函數返回的是一個新的列表,而不是對原有列表進行操作。
默認情況下,sorted()使用升序排列。如果要使用降序排列,則可以將參數reverse設置為True
對於對象列表而言,可以使用對象的某個屬性進行排序。這裡需要使用sorted()函數的key參數。
# 排序基礎示例: num_list = [2, 5, 1, 9, 3] sorted_list = sorted(num_list) # 默認升序 print(sorted_list) # [1, 2, 3, 5, 9] reverse_list = sorted(num_list, reverse=True) # 降序排列 print(reverse_list) # [9, 5, 3, 2, 1] word_list = ['cat', 'elephant', 'dog', 'bat'] sorted_words = sorted(word_list) # 默認按字典序排列 print(sorted_words) # ['bat', 'cat', 'dog', 'elephant'] len_words = sorted(word_list, key=len) # 以字元串長度排序 print(len_words) # ['cat', 'dog', 'bat', 'elephant']
二、自定義排序規則
對於一些特殊需求,需要使用自定義的排序規則。例如,進行不區分大小寫的排序,或是將某個單詞排在列表的最前面。
為了實現這個功能,可以使用sort()函數並自定義比較函數key。該函數可接受一個值並返回一個排序關鍵字。如果要使用自定義比較函數,則需要將參數key設置為該函數名。
# 排序規則的自定義示例: def to_lowercase(word): """將string小寫化然後返回""" return word.lower() words = ["Wombat", "Dog", "Cat", "Giraffe"] words.sort(key=to_lowercase) print(words) # ['Cat', 'Dog', 'Giraffe', 'Wombat']
三、按多個關鍵字排序
在排序時,如果有多個關鍵字,可以使用多重排序,即按照多個關鍵字進行排序。多重排序方法為:將多個排序關鍵字放入元組,將這些元組放入列表,然後使用sorted()函數進行排序即可。
# 按多個關鍵字排序示例: students = [ {"name": "Amy", "age": 31, "score": 80}, {"name": "Bob", "age": 24, "score": 90}, {"name": "Charlie", "age": 28, "score": 75}, {"name": "David", "age": 28, "score": 80}] sorted_students = sorted(students, key=lambda s: (s["age"], s["score"])) print(sorted_students)
四、使用numpy對多維列表進行排序
對於多維列表,numpy的sort方法是一個更好的選擇。使用numpy的sort函數可以對多維數組的任意列或行進行排序。
# 對多維列表的排序示例: import numpy as np data = np.array([[5, 9, 8], [4, 7, 6], [3, 2, 1]]) sorted_data = np.sort(data, axis=0) # 按列排序 print(sorted_data)
五、穩定排序和不穩定排序
穩定排序指輸入中相等的元素在輸出中的相對位置不發生改變。而不穩定排序則不保證相等元素的相對位置。
Python中的內置排序排序sorted()是穩定的排序。
# 穩定排序示例: words = ["Dog", "cat", "bat", "Timberwolf", "giraffe", "elephant", "cow"] sorted_words = sorted(words, key=str.lower) print(sorted_words) # ['bat', 'cat', 'cow', 'Dog', 'elephant', 'giraffe', 'Timberwolf']
六、使用operator模塊進行排序
Python的operator模塊提供了一些方便的函數,使之易於排序。
# operator模塊排序示例: import operator data = [("apple", 1), ("orange", 3), ("banana", 2)] sorted_data = sorted(data, key=operator.itemgetter(1)) print(sorted_data)
七、總結
Python中的列表可用於存儲和操作數據。對於Python列表的排序,主要使用內置函數sorted()。排序時,可以使用排序規則來滿足多種不同的需求,如自定義排序、多重排序。
對於特別大的列表,使用numpy的sort方法會更有效率。Python還提供了操作符模塊,對於某些特殊情況下的排序,則可以使用這些功能更方便的完成。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/155008.html