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

Python sorted函数完整使用教程 | 掌握Python排序技巧

Python sorted函数完全指南

掌握Python排序的艺术 - 从基础到高级用法

sorted函数简介

Python中的sorted()函数是用于排序的内置函数,它可以对任何可迭代对象进行排序并返回一个新的有序列表。与列表的sort()方法不同,sorted()函数不会改变原始数据,而是返回一个新的排序后的列表。

为什么使用sorted函数?

  • 可以对任何可迭代对象排序(列表、元组、字典等)
  • 返回一个新的排序列表,不改变原始数据
  • 支持自定义排序规则
  • 简单易用,功能强大
  • 在Python 2和Python 3中表现一致
注意: sorted()函数总是返回一个列表,无论输入是什么可迭代类型。
# 基本排序示例
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
sorted_numbers = sorted(numbers)

print("原始列表:", numbers)
print("排序后列表:", sorted_numbers)

# 输出结果:
# 原始列表: [3, 1, 4, 1, 5, 9, 2, 6]
# 排序后列表: [1, 1, 2, 3, 4, 5, 6, 9]

sorted函数基本语法

sorted()函数的基本语法如下:

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

参数说明:

参数 说明 默认值
iterable 必需,表示要排序的可迭代对象(列表、元组、字典、集合等)
key 可选,用于指定排序依据的函数 None
reverse 可选,排序顺序,True表示降序,False表示升序 False(升序)

sorted函数使用示例

1. 基本排序

对数字列表进行升序和降序排序:

2. 字符串排序

对字符串列表按字母顺序排序:

3. 复杂数据结构排序

对元组列表按特定元素排序:

# 1. 基本数字排序
numbers = [5, 2, 9, 1, 7]
ascending = sorted(numbers)  # 升序
descending = sorted(numbers, reverse=True)  # 降序

# 2. 字符串排序
fruits = ['apple', 'Banana', 'cherry', 'Date']
sorted_fruits = sorted(fruits)  # 区分大小写排序
case_insensitive = sorted(fruits, key=lambda s: s.lower())

# 3. 复杂数据结构排序
students = [
    ('Alice', 90),
    ('Bob', 75),
    ('Charlie', 95)
]
# 按分数排序
sorted_by_grade = sorted(students, key=lambda x: x[1])

key参数的高级用法

key参数是sorted函数最强大的功能之一,它允许我们自定义排序规则。key函数应用于每个元素,并返回一个用于排序的值。

按字符串长度排序

words = ['Python', 'is', 'awesome', 'for', 'sorting']
sorted_words = sorted(words, key=len)

# 结果: ['is', 'for', 'Python', 'sorting', 'awesome']

按字典值排序

student_scores = {
    'Alice': 90,
    'Bob': 75,
    'Charlie': 95
}
# 按分数排序并获取名字
sorted_names = sorted(student_scores, key=student_scores.get)

# 结果: ['Bob', 'Alice', 'Charlie']

多级排序

people = [
    {'name': 'Alice', 'age': 30, 'score': 90},
    {'name': 'Bob', 'age': 25, 'score': 95},
    {'name': 'Charlie', 'age': 30, 'score': 85}
]

# 先按年龄升序,再按分数降序
sorted_people = sorted(people, key=lambda x: (x['age'], -x['score']))

sorted与sort()方法的区别

特性 sorted()函数 list.sort()方法
适用范围 所有可迭代对象 仅列表
返回值 返回新列表 原地修改,返回None
原始数据 不改变原始数据 改变原始列表
链式调用 支持链式操作 不支持
使用示例 sorted(iterable) list.sort()
选择建议: 当需要保留原始数据时使用sorted()函数,当不需要原始数据且操作对象是列表时使用sort()方法。

排序算法与性能

Python的sorted()函数使用的是TimSort算法,这是一种混合排序算法,结合了归并排序和插入排序的优点。

TimSort特点:

  • 稳定排序(相等元素的相对位置不变)
  • 时间复杂度:O(n log n)
  • 对部分有序的数据效率很高
  • 实际应用中表现优异

性能注意事项:

  • 排序大列表时,sorted()会消耗额外内存
  • 复杂key函数可能影响性能
  • 对于小型数据集,sorted()和sort()性能差异很小
# 性能比较示例
import timeit

setup = "import random; data = [random.randint(0, 1000) for _ in range(10000)]"

# 测试sorted()函数
sorted_time = timeit.timeit("sorted(data)", setup, number=100)

# 测试list.sort()方法
sort_time = timeit.timeit("data.sort()", setup, number=100)

print(f"sorted() 用时: {sorted_time:.4f} 秒")
print(f"sort() 用时: {sort_time:.4f} 秒")

# 典型输出:
# sorted() 用时: 0.4521 秒
# sort() 用时: 0.3127 秒

Python sorted函数教程 | 掌握排序技巧,提高编程效率

发表评论