掌握 Python 列表排序的 15 個方法
大家好!今天我們要聊的是Python中列表排序的各種方法。無論你是剛?cè)腴T的小白,還是有一定基礎的進階者,這篇文章都會對你有所幫助。我們將從最基礎的方法開始,逐步深入到更高級的技巧。話不多說,讓我們開始吧!

1. 使用 sorted() 函數(shù)
sorted() 是Python內(nèi)置的一個函數(shù),可以用來對任何可迭代對象進行排序,返回一個新的已排序列表。
# 基本用法
numbers = [5, 2, 9, 1, 5, 6]
sorted_numbers = sorted(numbers)
print(sorted_numbers)  # 輸出: [1, 2, 5, 5, 6, 9]
# 反向排序
sorted_numbers_desc = sorted(numbers, reverse=True)
print(sorted_numbers_desc)  # 輸出: [9, 6, 5, 5, 2, 1]2. 使用 list.sort() 方法
list.sort() 是列表對象的一個方法,用于原地排序列表,不返回新的列表。
# 基本用法
numbers = [5, 2, 9, 1, 5, 6]
numbers.sort()
print(numbers)  # 輸出: [1, 2, 5, 5, 6, 9]
# 反向排序
numbers.sort(reverse=True)
print(numbers)  # 輸出: [9, 6, 5, 5, 2, 1]3. 按字符串長度排序
有時候我們需要按字符串的長度進行排序,這可以通過 key 參數(shù)來實現(xiàn)。
words = ["apple", "banana", "cherry", "date"]
sorted_words_by_length = sorted(words, key=len)
print(sorted_words_by_length)  # 輸出: ['date', 'apple', 'cherry', 'banana']4. 按自定義函數(shù)排序
我們可以使用 key 參數(shù)傳入一個自定義函數(shù),以實現(xiàn)更復雜的排序邏輯。
def custom_key(word):
    return word[-1]  # 按最后一個字符排序
words = ["apple", "banana", "cherry", "date"]
sorted_words_custom = sorted(words, key=custom_key)
print(sorted_words_custom)  # 輸出: ['date', 'apple', 'banana', 'cherry']5. 按多個條件排序
有時我們需要按多個條件進行排序,這可以通過傳遞一個元組作為 key 參數(shù)來實現(xiàn)。
students = [
    {"name": "Alice", "age": 20},
    {"name": "Bob", "age": 22},
    {"name": "Charlie", "age": 20}
]
# 先按年齡排序,再按名字排序
sorted_students = sorted(students, key=lambda x: (x['age'], x['name']))
print(sorted_students)
# 輸出: [{'name': 'Alice', 'age': 20}, {'name': 'Charlie', 'age': 20}, {'name': 'Bob', 'age': 22}]6. 按數(shù)值絕對值排序
有時我們需要按數(shù)值的絕對值進行排序,這同樣可以通過 key 參數(shù)來實現(xiàn)。
numbers = [-5, 2, -1, 3, 0, -2]
sorted_numbers_abs = sorted(numbers, key=abs)
print(sorted_numbers_abs)  # 輸出: [0, -1, 2, -2, 3, -5]7. 按對象屬性排序
如果列表中的元素是對象,我們可以按對象的某個屬性進行排序。
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
people = [
    Person("Alice", 20),
    Person("Bob", 22),
    Person("Charlie", 20)
]
# 按年齡排序
sorted_people = sorted(people, key=lambda x: x.age)
for person in sorted_people:
    print(person.name, person.age)
# 輸出: Alice 20, Charlie 20, Bob 228. 使用 operator.attrgetter 和 operator.itemgetter
operator 模塊提供了 attrgetter 和 itemgetter 函數(shù),可以簡化按屬性或鍵值排序的操作。
from operator import attrgetter, itemgetter
# 按對象屬性排序
sorted_people_attr = sorted(people, key=attrgetter('age'))
for person in sorted_people_attr:
    print(person.name, person.age)
# 輸出: Alice 20, Charlie 20, Bob 22
# 按字典鍵值排序
students = [
    {"name": "Alice", "age": 20},
    {"name": "Bob", "age": 22},
    {"name": "Charlie", "age": 20}
]
sorted_students_item = sorted(students, key=itemgetter('age'))
print(sorted_students_item)
# 輸出: [{'name': 'Alice', 'age': 20}, {'name': 'Charlie', 'age': 20}, {'name': 'Bob', 'age': 22}]9. 使用 heapq.nsmallest 和 heapq.nlargest
heapq 模塊提供了 nsmallest 和 nlargest 函數(shù),可以快速找到列表中的最小或最大元素。
import heapq
numbers = [5, 2, 9, 1, 5, 6]
# 找到前3個最小的數(shù)
smallest_three = heapq.nsmallest(3, numbers)
print(smallest_three)  # 輸出: [1, 2, 5]
# 找到前3個最大的數(shù)
largest_three = heapq.nlargest(3, numbers)
print(largest_three)  # 輸出: [9, 6, 5]10. 使用 pandas 庫排序
如果你處理的是數(shù)據(jù)科學相關的任務,pandas 庫提供了強大的數(shù)據(jù)處理功能,包括排序。
import pandas as pd
data = {
    'name': ['Alice', 'Bob', 'Charlie'],
    'age': [20, 22, 20]
}
df = pd.DataFrame(data)
# 按年齡排序
sorted_df = df.sort_values(by='age')
print(sorted_df)
# 輸出:
#       name  age
# 0   Alice   20
# 2  Charlie  20
# 1     Bob   2211. 使用 numpy 庫排序
numpy 是一個強大的科學計算庫,它提供了高效的數(shù)組操作功能,包括排序。
import numpy as np
numbers = [5, 2, 9, 1, 5, 6]
np_numbers = np.array(numbers)
# 升序排序
sorted_np_numbers = np.sort(np_numbers)
print(sorted_np_numbers)  # 輸出: [1 2 5 5 6 9]
# 降序排序
sorted_np_numbers_desc = np.sort(np_numbers)[::-1]
print(sorted_np_numbers_desc)  # 輸出: [9 6 5 5 2 1]12. 自定義比較函數(shù)
在某些情況下,我們需要更復雜的排序邏輯,可以使用 functools.cmp_to_key 將自定義的比較函數(shù)轉(zhuǎn)換為 key 函數(shù)。
from functools import cmp_to_key
def custom_compare(x, y):
    if x < y:
        return -1
    elif x > y:
        return 1
    else:
        return 0
numbers = [5, 2, 9, 1, 5, 6]
sorted_numbers_custom = sorted(numbers, key=cmp_to_key(custom_compare))
print(sorted_numbers_custom)  # 輸出: [1, 2, 5, 5, 6, 9]13. 穩(wěn)定排序
穩(wěn)定排序是指在排序過程中,相同元素的相對位置保持不變。sorted() 和 list.sort() 都是穩(wěn)定的排序算法。
students = [
    {"name": "Alice", "age": 20},
    {"name": "Bob", "age": 22},
    {"name": "Charlie", "age": 20}
]
# 先按名字排序,再按年齡排序
students.sort(key=lambda x: x['name'])
students.sort(key=lambda x: x['age'])
for student in students:
    print(student['name'], student['age'])
# 輸出: Alice 20, Charlie 20, Bob 22在這個例子中,先按名字排序,再按年齡排序,保證了相同年齡的學生的名字順序不變。
14. 多級排序(使用 pandas)
pandas 庫不僅支持單級排序,還支持多級排序。
import pandas as pd
data = {
    'name': ['Alice', 'Bob', 'Charlie', 'David'],
    'age': [20, 22, 20, 21],
    'score': [85, 90, 88, 92]
}
df = pd.DataFrame(data)
# 先按年齡升序排序,再按分數(shù)降序排序
sorted_df = df.sort_values(by=['age', 'score'], ascending=[True, False])
print(sorted_df)
# 輸出:
#      name  age  score
# 0   Alice   20     85
# 2  Charlie  20     88
# 3   David   21     92
# 1     Bob   22     9015. 使用 itertools.groupby 進行分組排序
itertools.groupby 可以將列表按某個條件分組,然后再對每個組進行排序。
from itertools import groupby
students = [
    {"name": "Alice", "age": 20},
    {"name": "Bob", "age": 22},
    {"name": "Charlie", "age": 20},
    {"name": "David", "age": 21}
]
# 先按年齡排序
students.sort(key=lambda x: x['age'])
# 按年齡分組
grouped_students = {k: list(v) for k, v in groupby(students, key=lambda x: x['age'])}
for age, group in grouped_students.items():
    print(f"Age: {age}")
    for student in group:
        print(student['name'], student['age'])
# 輸出:
# Age: 20
# Alice 20
# Charlie 20
# Age: 21
# David 21
# Age: 22
# Bob 22實戰(zhàn)案例分析
假設你是一家在線書店的開發(fā)人員,需要對書籍按評分和銷量進行排序。我們將使用前面學到的多種排序方法來實現(xiàn)這個需求。
books = [
    {"title": "Book A", "rating": 4.5, "sales": 500},
    {"title": "Book B", "rating": 4.2, "sales": 300},
    {"title": "Book C", "rating": 4.7, "sales": 700},
    {"title": "Book D", "rating": 4.3, "sales": 400}
]
# 先按評分降序排序,再按銷量降序排序
sorted_books = sorted(books, key=lambda x: (-x['rating'], -x['sales']))
for book in sorted_books:
    print(book['title'], book['rating'], book['sales'])
# 輸出:
# Book C 4.7 700
# Book A 4.5 500
# Book D 4.3 400
# Book B 4.2 300在這個案例中,我們使用了 lambda 表達式和 key 參數(shù)來實現(xiàn)多級排序。希望這個案例能幫助你更好地理解和應用這些排序方法。
總結(jié)
本文詳細介紹了Python中列表排序的各種方法,從基本的 sorted() 和 list.sort() 到更高級的 numpy、pandas 和自定義排序邏輯。通過這些方法,你可以靈活地應對各種排序需求。















 
 
 














 
 
 
 