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

作者:

文章目录
  • sorted() 函数的核心要点: 基础用法:对可迭代对象排序,返回新列表。 关键参数: key:自定义排序依据,接收单参数函数。 reverse:控制升序 / 降序。 高级技巧: 通过返回元组实现多级排序。 使用 cmp_to_key 处理复杂比较逻辑。 性能特点:时间复杂度 O (n log n),排序稳定。 掌握 sorted() 能让你高效处理各种排序需求,从简单列表到复杂对象集合都能轻松应对。合理使用 key 和 reverse 参数是实现灵活排序的关键。
  • 以上为个人经验,希望能给大家一个参考,也希望大家多多支持风君子博客。 您可能感兴趣的文章: python函数之sorted函数和lambda函数用法详解 python sorted()函数的key参数使用说明 Python中的sort方法、sorted函数与lambda表达式及用法详解 python中常用排序操作sort方法和sorted函数的使用超详细讲解(内置模板代码!) Python中sorted()函数之排序的利器详解 Python中sorted()函数的强大排序技术实例探索
  • 目录
    • 一、基础语法与核心功能
      • 1. 基本语法
      • 2. 简单示例
    • 二、关键参数详解
      • 1.key参数:自定义排序依据
      • 2.reverse参数:降序排序
    • 三、复杂对象排序
      • 1. 自定义类对象排序
      • 2. 字典排序
    • 四、多条件排序
      • 1. 多级排序
      • 2. 组合多个排序条件
    • 五、性能与稳定性
      • 1. 时间复杂度
      • 2. 稳定性
    • 六、实战应用场景
      • 1. 数据筛选与排名
      • 2. 自定义排序逻辑
      • 3. 处理非可比对象
    • 七、总结
      • 总结

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

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

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

        参数

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

        # 列表排序
        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']

        • 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)]

        • reverse=True 表示降序排列。
        numbers = [3, 1, 4, 1, 5, 9, 2]
        descending = sorted(numbers, reverse=True)
        print(descending)  # 输出: [9, 5, 4, 3, 2, 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)]

        • 对字典排序时,默认按键排序;如需按键值排序,需指定 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)]

        • 通过返回元组实现多级排序(优先级从左到右)。
        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)]

        • 使用 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']

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

        • 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') 前,排序后保持此顺序

        # 筛选前 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', ...}]

        # 特殊排序规则(负数排前,正数按绝对值排)
        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]

        # 对不可直接比较的对象排序
        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函数之sorted函数和lambda函数用法详解
        • python sorted()函数的key参数使用说明
        • Python中的sort方法、sorted函数与lambda表达式及用法详解
        • python中常用排序操作sort方法和sorted函数的使用超详细讲解(内置模板代码!)
        • Python中sorted()函数之排序的利器详解
        • Python中sorted()函数的强大排序技术实例探索

        站内搜索