当前位置: 代码网 > it编程>前端脚本>Python > Python之sorted函数使用与实战过程

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

2026年02月03日 Python 我要评论
sorted()是 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 参数是实现灵活排序的关键。

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com