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

Python列表排序完全指南:sort()与sorted()方法详解 | Python排序教程

Python列表排序完全指南

掌握sort()与sorted()两种排序方法,提升数据处理效率

Python列表排序的重要性

在数据处理和算法实现中,排序是最常用的操作之一。Python提供了两种主要的排序方法:sort()sorted(),它们各有特点,适用于不同的场景。

sort()方法

  • 原地排序(修改原列表)
  • 无返回值(返回None)
  • 仅适用于列表
  • 内存效率高

sorted()函数

  • 返回新排序列表(原列表不变)
  • 可用于任何可迭代对象
  • 更灵活,应用范围广
  • 需要额外内存空间

注意: 两种方法都使用Timsort算法,这是一种结合了归并排序和插入排序的混合算法,时间复杂度为O(n log n)。

sort()方法详解

基本用法

list.sort(key=None, reverse=False)


# 基本数字排序
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
numbers.sort()
print(numbers)  # 输出: [1, 1, 2, 3, 4, 5, 6, 9]

# 字符串排序
fruits = ['banana', 'apple', 'cherry', 'date']
fruits.sort()
print(fruits)  # 输出: ['apple', 'banana', 'cherry', 'date']

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

使用key参数自定义排序


# 按字符串长度排序
words = ['Python', 'is', 'awesome', 'for', 'data', 'analysis']
words.sort(key=len)
print(words)  # 输出: ['is', 'for', 'data', 'Python', 'awesome', 'analysis']

# 按元组中第二个元素排序
pairs = [(1, 5), (3, 2), (2, 8), (4, 1)]
pairs.sort(key=lambda x: x[1])
print(pairs)  # 输出: [(4, 1), (3, 2), (1, 5), (2, 8)]

# 复杂对象排序
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
        
people = [
    Person('Alice', 30),
    Person('Bob', 25),
    Person('Charlie', 35)
]

people.sort(key=lambda p: p.age)
print([p.name for p in people])  # 输出: ['Bob', 'Alice', 'Charlie']
                

sorted()函数详解

基本用法

sorted(iterable, key=None, reverse=False)


# 排序列表(原列表不变)
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
sorted_numbers = sorted(numbers)
print(sorted_numbers)  # 输出: [1, 1, 2, 3, 4, 5, 6, 9]
print(numbers)         # 输出: [3, 1, 4, 1, 5, 9, 2, 6] (原列表不变)

# 排序字符串
text = "python"
sorted_text = sorted(text)
print(sorted_text)  # 输出: ['h', 'n', 'o', 'p', 't', 'y']
print(''.join(sorted_text))  # 输出: 'hnopty'

# 排序字典
student_scores = {'Alice': 85, 'Bob': 72, 'Charlie': 90, 'David': 68}
# 按键排序
sorted_by_name = sorted(student_scores.items())
print(sorted_by_name)  # 输出: [('Alice', 85), ('Bob', 72), ('Charlie', 90), ('David', 68)]

# 按值排序
sorted_by_score = sorted(student_scores.items(), key=lambda x: x[1])
print(sorted_by_score)  # 输出: [('David', 68), ('Bob', 72), ('Alice', 85), ('Charlie', 90)]
                

高级排序技巧


# 多级排序(先按成绩降序,再按姓名升序)
students = [
    {'name': 'Alice', 'score': 85, 'age': 20},
    {'name': 'Bob', 'score': 85, 'age': 22},
    {'name': 'Charlie', 'score': 90, 'age': 19},
    {'name': 'David', 'score': 68, 'age': 21}
]

# 先按score降序,再按name升序
sorted_students = sorted(students, key=lambda x: (-x['score'], x['name']))
for student in sorted_students:
    print(f"{student['name']}: {student['score']}")

# 输出:
# Charlie: 90
# Alice: 85
# Bob: 85
# David: 68

# 使用多个key进行排序
# 先按score降序,再按age升序
sorted_students = sorted(students, key=lambda x: (x['score'], x['age']), reverse=True)
# 这样写的问题是score和age都会降序排列

# 更好的方式:
sorted_students = sorted(students, key=lambda x: (-x['score'], x['age']))
                

sort() vs sorted():如何选择?

特性 sort() sorted()
修改原列表
返回值 None 新排序列表
适用对象 仅列表 任何可迭代对象
内存使用 低(原地排序) 高(创建新列表)
使用场景 当不需要保留原列表时 需要保留原列表或排序不可变对象时

选择指南

✅ 使用sort()当:

  • 排序后不再需要原始列表顺序
  • 处理大型列表且关心内存使用
  • 只处理列表对象

✅ 使用sorted()当:

  • 需要保留原始数据不变
  • 排序不可变对象(如元组、字符串)
  • 需要将排序结果用于链式操作
  • 排序字典或其他可迭代对象

© 2023 Python排序教程 | 本教程仅供学习参考

发表评论