当前位置:首页 > Python > 正文

Python排序方法详解:列表排序、字典排序与高级排序技巧

Python排序方法完全指南

掌握sorted()函数、sort()方法以及各种高级排序技巧

为什么排序在编程中如此重要?

排序是数据处理中的基础操作,Python提供了多种高效灵活的排序方法。无论是简单的数字列表还是复杂的自定义对象,Python都能轻松应对。

在本教程中,您将学习:

  • 使用sorted()函数和sort()方法
  • 对列表、元组和字典进行排序
  • 自定义排序规则和关键字
  • 多级排序和稳定排序
  • 复杂数据结构的排序技巧

基础排序方法

1. 列表排序 - sort()方法

sort()方法会直接修改原列表,不返回新列表:

numbers = [3, 1, 4, 1, 5, 9, 2, 6]
numbers.sort()
print(numbers)  # 输出: [1, 1, 2, 3, 4, 5, 6, 9]

# 降序排序
numbers.sort(reverse=True)
print(numbers)  # 输出: [9, 6, 5, 4, 3, 2, 1, 1]

2. sorted()函数

sorted()函数返回一个新的排序列表,不改变原始数据:

fruits = ['apple', 'Banana', 'cherry', 'Date']
sorted_fruits = sorted(fruits)
print(sorted_fruits)  # 输出: ['Banana', 'Date', 'apple', 'cherry'] (区分大小写)

# 不区分大小写排序
sorted_fruits_ignore_case = sorted(fruits, key=str.lower)
print(sorted_fruits_ignore_case)  # 输出: ['apple', 'Banana', 'cherry', 'Date']

字典排序技巧

按键排序

student_scores = {'Alice': 92, 'Bob': 87, 'Charlie': 95, 'David': 78}

# 按键排序(默认)
sorted_by_name = sorted(student_scores.items())
print(sorted_by_name)
# 输出: [('Alice', 92), ('Bob', 87), ('Charlie', 95), ('David', 78)]

按值排序

# 按值升序排序
sorted_by_score = sorted(student_scores.items(), key=lambda item: item[1])
print(sorted_by_score)
# 输出: [('David', 78), ('Bob', 87), ('Alice', 92), ('Charlie', 95)]

# 按值降序排序
sorted_by_score_desc = sorted(student_scores.items(), key=lambda item: item[1], reverse=True)
print(sorted_by_score_desc)
# 输出: [('Charlie', 95), ('Alice', 92), ('Bob', 87), ('David', 78)]

高级排序技巧

1. 多级排序

# 学生数据:姓名、成绩、年龄
students = [
    ('Alice', 'B', 20),
    ('Bob', 'A', 18),
    ('Charlie', 'B', 22),
    ('David', 'A', 19)
]

# 先按成绩升序,再按年龄降序
sorted_students = sorted(students, key=lambda s: (s[1], -s[2]))
print(sorted_students)
# 输出: [('David', 'A', 19), ('Bob', 'A', 18), ('Charlie', 'B', 22), ('Alice', 'B', 20)]

2. 自定义排序函数

# 按字符串长度排序,相同长度按字母顺序
words = ['banana', 'pie', 'Washington', 'book', 'sky', 'apple']

# 自定义排序函数
def custom_sort(word):
    return (len(word), word.lower())

sorted_words = sorted(words, key=custom_sort)
print(sorted_words)
# 输出: ['pie', 'sky', 'book', 'apple', 'banana', 'Washington']

3. 对象列表排序

class Product:
    def __init__(self, name, price, category):
        self.name = name
        self.price = price
        self.category = category
        
    def __repr__(self):
        return f"{self.category}: {self.name} (${self.price})"

products = [
    Product('Laptop', 1200, 'Electronics'),
    Product('Shirt', 35, 'Clothing'),
    Product('Desk', 250, 'Furniture'),
    Product('Phone', 800, 'Electronics'),
    Product('Jeans', 60, 'Clothing')
]

# 按类别升序,再按价格降序
sorted_products = sorted(products, key=lambda p: (p.category, -p.price))
for product in sorted_products:
    print(product)

# 输出:
# Clothing: Shirt ($35)
# Clothing: Jeans ($60)
# Electronics: Laptop ($1200)
# Electronics: Phone ($800)
# Furniture: Desk ($250)

Python排序算法比较

方法 是否原地排序 适用对象 时间复杂度 特点
list.sort() 列表 O(n log n) 最常用,直接修改原列表
sorted() 任何可迭代对象 O(n log n) 返回新列表,不影响原始数据
operator.itemgetter - 字典、元组等 O(n log n) 比lambda表达式更高效

最佳实践建议:

  • 对于大型数据集,使用key参数比cmp参数更高效
  • 如果需要保留原始数据,使用sorted()而不是sort()
  • 对自定义对象排序时,实现__lt__方法可支持自然排序
  • Python的排序是稳定排序,相同元素保持原始顺序
  • 使用operator模块可以提高排序效率

Python排序方法教程 © 2023 - 掌握Python排序技巧,提升数据处理能力

发表评论