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

Python sorted()函数参数用法详解 - 全面教程

Python sorted()函数参数用法详解

Python内置的sorted()函数是数据处理中常用的排序工具,它提供了强大的排序功能,支持对列表、元组、字典等各种可迭代对象进行排序。本教程将深入讲解sorted()函数的参数用法,特别是keyreverse参数的高级应用。

一、sorted()函数基本语法

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

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

参数说明:

  • iterable - 必需,要排序的可迭代对象
  • key - 可选,用于指定排序规则的函数
  • reverse - 可选,布尔值,True表示降序,False表示升序(默认)

二、reverse参数用法

reverse参数控制排序顺序,默认为False(升序),设置为True则为降序排序。

升序排序(默认)

numbers = [5, 2, 8, 1, 9]
sorted_numbers = sorted(numbers)
print(sorted_numbers)  # 输出: [1, 2, 5, 8, 9]

降序排序

numbers = [5, 2, 8, 1, 9]
sorted_numbers = sorted(numbers, reverse=True)
print(sorted_numbers)  # 输出: [9, 8, 5, 2, 1]

三、key参数详解

key参数是sorted()函数最强大的功能,它允许我们通过一个函数来自定义排序规则。

1. 使用内置函数作为key

# 按字符串长度排序
words = ["apple", "banana", "cherry", "date"]
sorted_words = sorted(words, key=len)
print(sorted_words)  # 输出: ['date', 'apple', 'banana', 'cherry']

# 按绝对值大小排序
numbers = [-5, 3, -2, 8, -1]
sorted_abs = sorted(numbers, key=abs)
print(sorted_abs)  # 输出: [-1, -2, 3, -5, 8]

2. 使用lambda表达式作为key

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

# 按字典的值排序
student_scores = {"Alice": 85, "Bob": 92, "Charlie": 78, "David": 88}
sorted_scores = sorted(student_scores.items(), key=lambda x: x[1], reverse=True)
print(sorted_scores)  # 输出: [('Bob', 92), ('David', 88), ('Alice', 85), ('Charlie', 78)]

3. 使用自定义函数作为key

# 自定义排序函数:按成绩等级排序
def grade_score(score):
    if score >= 90:
        return 0  # 最高优先级
    elif score >= 80:
        return 1
    elif score >= 70:
        return 2
    else:
        return 3

scores = [85, 92, 65, 78, 95, 88]
sorted_by_grade = sorted(scores, key=grade_score)
print(sorted_by_grade)  # 输出: [92, 95, 85, 88, 78, 65]

4. 多级排序技巧

# 先按成绩降序,再按姓名升序
students = [
    {"name": "Alice", "score": 85},
    {"name": "Bob", "score": 92},
    {"name": "Charlie", "score": 85},
    {"name": "David", "score": 92}
]

# 技巧:返回元组实现多级排序
sorted_students = sorted(students, key=lambda x: (-x['score'], x['name']))
for student in sorted_students:
    print(f"{student['name']}: {student['score']}")

# 输出:
# Bob: 92
# David: 92
# Alice: 85
# Charlie: 85

四、排序稳定性说明

Python的sorted()函数是稳定排序,这意味着当多个元素具有相同的排序键时,它们将保持原有的相对顺序。这个特性对于多级排序非常有用。

五、sorted()与sort()的区别

特性 sorted() sort()
返回类型 返回新的排序列表 原地排序,返回None
适用对象 任何可迭代对象 仅列表
原始数据 不改变原始数据 改变原始列表

六、实际应用场景

文件名排序

files = ["file10.txt", "file2.txt", 
         "file1.txt", "file20.txt"]
# 自然排序(按数字大小)
sorted_files = sorted(files, 
    key=lambda x: int(x[4:-4]))
print(sorted_files)

JSON数据处理

data = [
    {"name": "Alice", "age": 30},
    {"name": "Bob", "age": 25},
    {"name": "Charlie", "age": 35}
]
# 按年龄排序
sorted_data = sorted(data, 
    key=lambda x: x["age"])
print(sorted_data)

总结

Python的sorted()函数是一个非常强大的排序工具,通过合理使用其参数可以解决各种复杂的排序需求:

  1. 使用reverse参数控制升序或降序排列
  2. 使用key参数定义自定义排序规则
  3. 结合lambda表达式简化代码
  4. 利用元组实现多级排序
  5. 注意sorted()与list.sort()的区别

掌握sorted()函数的参数用法将大大提高你在数据处理和算法实现中的效率,是每个Python开发者必备的核心技能。

发表评论