python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > Python之sorted函数使用与实战

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

作者:alden_ygq

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

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

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

一、基础语法与核心功能

1. 基本语法

sorted(iterable, *, key=None, 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参数:自定义排序依据

# 按字符串长度排序
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参数:降序排序

numbers = [3, 1, 4, 1, 5, 9, 2]
descending = sorted(numbers, reverse=True)
print(descending)  # 输出: [9, 5, 4, 3, 2, 1, 1]

三、复杂对象排序

1. 自定义类对象排序

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. 字典排序

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. 组合多个排序条件

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. 时间复杂度

2. 稳定性

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() 函数的核心要点:

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

关键参数

高级技巧

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

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

总结

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

您可能感兴趣的文章:
阅读全文