Python之sorted函数使用与实战过程

 更新时间:2026年02月03日 09:14:06   作者:alden_ygq  
本文详细介绍了Python中`sorted()`函数的用法,包括基础语法、关键参数、复杂对象排序、多条件排序、性能与稳定性以及实战应用场景,通过这些内容,读者可以掌握如何高效地对各种可迭代对象进行排序

sorted() 是 Python 中用于对可迭代对象进行排序的内置函数,返回一个新的已排序列表,原对象保持不变。

本文将深入解析 sorted() 的用法、参数及实战技巧,帮助你掌握各种排序场景。

一、基础语法与核心功能

1. 基本语法

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

参数

  • iterable:必需,可迭代对象(如列表、元组、集合、字典等)。
  • key:可选,指定排序依据的函数(如 lenstr.lower)。
  • reverse:可选,布尔值,是否降序排序(默认 False 升序)。
  • 返回值:新的已排序列表。

2. 简单示例

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

# 元组排序(返回列表)
tuple_data = (5, 3, 1)
sorted_list = sorted(tuple_data)
print(sorted_list)  # 输出: [1, 3, 5]

# 字符串排序(按字符编码)
text = "python"
sorted_chars = sorted(text)
print(sorted_chars)  # 输出: ['h', 'n', 'o', 'p', 't', 'y']

二、关键参数详解

1.key参数:自定义排序依据

  • key 接收一个函数,该函数用于从每个元素中提取排序依据。
# 按字符串长度排序
words = ["apple", "banana", "cherry", "date"]
sorted_words = sorted(words, key=len)
print(sorted_words)  # 输出: ['date', 'apple', 'cherry', 'banana']

# 按小写字母排序
mixed_case = ["banana", "Apple", "Cherry"]
sorted_case_insensitive = sorted(mixed_case, key=str.lower)
print(sorted_case_insensitive)  # 输出: ['Apple', 'banana', 'Cherry']

# 按元组的第二个元素排序
data = [(1, 5), (3, 1), (2, 8)]
sorted_data = sorted(data, key=lambda x: x[1])
print(sorted_data)  # 输出: [(3, 1), (1, 5), (2, 8)]

2.reverse参数:降序排序

  • reverse=True 表示降序排列。
numbers = [3, 1, 4, 1, 5, 9, 2]
descending = sorted(numbers, reverse=True)
print(descending)  # 输出: [9, 5, 4, 3, 2, 1, 1]

三、复杂对象排序

1. 自定义类对象排序

  • 通过 key 指定排序依据的属性或方法。
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def __repr__(self):
        return f"Person({self.name}, {self.age})"

people = [Person("Alice", 25), Person("Bob", 20), Person("Charlie", 30)]

# 按年龄排序
sorted_people = sorted(people, key=lambda p: p.age)
print(sorted_people)  # 输出: [Person(Bob, 20), Person(Alice, 25), Person(Charlie, 30)]

2. 字典排序

  • 对字典排序时,默认按键排序;如需按键值排序,需指定 key
scores = {"Alice": 85, "Bob": 92, "Charlie": 78}

# 按键排序
sorted_keys = sorted(scores)
print(sorted_keys)  # 输出: ['Alice', 'Bob', 'Charlie']

# 按值排序(返回键的列表)
sorted_by_value = sorted(scores, key=lambda k: scores[k])
print(sorted_by_value)  # 输出: ['Charlie', 'Alice', 'Bob']

# 按值排序(返回元组列表)
sorted_items = sorted(scores.items(), key=lambda item: item[1])
print(sorted_items)  # 输出: [('Charlie', 78), ('Alice', 85), ('Bob', 92)]

四、多条件排序

1. 多级排序

  • 通过返回元组实现多级排序(优先级从左到右)。
students = [
    ("Alice", 25, 85),
    ("Bob", 20, 92),
    ("Charlie", 25, 78)
]  # 格式:(姓名, 年龄, 分数)

# 先按年龄升序,再按分数降序
sorted_students = sorted(students, key=lambda s: (s[1], -s[2]))
print(sorted_students)  # 输出: [('Bob', 20, 92), ('Charlie', 25, 78), ('Alice', 25, 85)]

2. 组合多个排序条件

  • 使用 functools.cmp_to_key 将比较函数转换为 key 函数。
from functools import cmp_to_key

def custom_compare(a, b):
    # 先按长度降序,长度相同则按字母升序
    if len(a) != len(b):
        return len(b) - len(a)
    return (a > b) - (a < b)  # 字符串比较

words = ["apple", "banana", "cherry", "date", "elder"]
sorted_words = sorted(words, key=cmp_to_key(custom_compare))
print(sorted_words)  # 输出: ['banana', 'cherry', 'elder', 'apple', 'date']

五、性能与稳定性

1. 时间复杂度

  • sorted() 的时间复杂度为 O(n log n),其中 n 是元素数量。
  • 对于大规模数据,可考虑使用 list.sort() 原地排序(性能略高)。

2. 稳定性

  • Python 的排序算法是稳定的,即相等元素的相对顺序保持不变。
data = [(1, 'a'), (2, 'b'), (1, 'c')]
sorted_data = sorted(data, key=lambda x: x[0])
print(sorted_data)  # 输出: [(1, 'a'), (1, 'c'), (2, 'b')]
# 原数据中 (1, 'a') 在 (1, 'c') 前,排序后保持此顺序

六、实战应用场景

1. 数据筛选与排名

# 筛选前 N 个元素
numbers = [3, 1, 4, 1, 5, 9, 2]
top_three = sorted(numbers, reverse=True)[:3]
print(top_three)  # 输出: [9, 5, 4]

# 按条件筛选并排序
people = [
    {"name": "Alice", "age": 25, "score": 85},
    {"name": "Bob", "age": 20, "score": 92},
    {"name": "Charlie", "age": 30, "score": 78}
]

adult_high_scores = sorted(
    [p for p in people if p["age"] >= 25],
    key=lambda p: p["score"],
    reverse=True
)
print(adult_high_scores)  # 输出: [{'name': 'Alice', ...}, {'name': 'Charlie', ...}]

2. 自定义排序逻辑

# 特殊排序规则(负数排前,正数按绝对值排)
numbers = [5, -3, 2, -7, 1]
sorted_numbers = sorted(numbers, key=lambda x: (x < 0, abs(x)))
print(sorted_numbers)  # 输出: [-3, -7, 1, 2, 5]

3. 处理非可比对象

# 对不可直接比较的对象排序
class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    
    def distance_from_origin(self):
        return (self.x**2 + self.y**2) ** 0.5

points = [Point(3, 4), Point(0, 1), Point(1, 1)]
sorted_points = sorted(points, key=lambda p: p.distance_from_origin())
print([(p.x, p.y) for p in sorted_points])  # 输出: [(0, 1), (1, 1), (3, 4)]

七、总结

sorted() 函数的核心要点:

基础用法:对可迭代对象排序,返回新列表。

关键参数

  • key:自定义排序依据,接收单参数函数。
  • reverse:控制升序 / 降序。

高级技巧

  • 通过返回元组实现多级排序。
  • 使用 cmp_to_key 处理复杂比较逻辑。

性能特点:时间复杂度 O (n log n),排序稳定。

掌握 sorted() 能让你高效处理各种排序需求,从简单列表到复杂对象集合都能轻松应对。合理使用 key 和 reverse 参数是实现灵活排序的关键。

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • Python线性回归图文实例详解

    Python线性回归图文实例详解

    用python进行线性回归分析非常方便,有现成的库可以使用比如numpy.linalog.lstsq、scipy.stats.linregress、pandas.ols等,这篇文章主要给大家介绍了关于Python线性回归的相关资料,需要的朋友可以参考下
    2021-11-11
  • Python缺少库IPython的解决办法步骤

    Python缺少库IPython的解决办法步骤

    在使用Python编写程序过程中,有时我们会遇到一些错误信息,提示我们当前环境缺少某些依赖库文件,这篇文章主要给大家介绍了关于Python缺少库IPython的解决办法步骤,需要的朋友可以参考下
    2023-12-12
  • python向xls写入数据(包括合并,边框,对齐,列宽)

    python向xls写入数据(包括合并,边框,对齐,列宽)

    这篇文章主要介绍了python向xls写入数据(包括合并,边框,对齐,列宽),帮助大家更好的利用python处理表格,感兴趣的朋友可以了解下
    2021-02-02
  • tensorflow 只恢复部分模型参数的实例

    tensorflow 只恢复部分模型参数的实例

    今天小编就为大家分享一篇tensorflow 只恢复部分模型参数的实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-01-01
  • 基于python纯函数实现井字棋游戏

    基于python纯函数实现井字棋游戏

    这篇文章主要介绍了基于python纯函数实现井字棋游戏,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-05-05
  • tensorflow中next_batch的具体使用

    tensorflow中next_batch的具体使用

    本篇文章主要介绍了tensorflow中next_batch的具体使用,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-02-02
  • Pycharm如何运行.py文件的方法步骤

    Pycharm如何运行.py文件的方法步骤

    这篇文章主要介绍了Pycharm如何运行.py文件的方法步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-03-03
  • centos6.8安装python3.7无法import _ssl的解决方法

    centos6.8安装python3.7无法import _ssl的解决方法

    这篇文章主要介绍了centos6.8安装python3.7无法import _ssl的解决方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-09-09
  • python如何快速拼接字符串

    python如何快速拼接字符串

    这篇文章主要介绍了python如何快速拼接字符串,帮助大家理解和学习python,感兴趣的朋友可以了解下
    2020-10-10
  • Python函数作用域示例详解

    Python函数作用域示例详解

    本文介绍了Python中的LEGB作用域规则,详细解析了变量查找的四个层级,通过具体代码示例,展示了各层级的变量访问规则和特性,对python函数作用域相关知识感兴趣的朋友一起看看吧
    2025-07-07

最新评论