Python排序函数sortedkey详解

发布时间:2023-05-22

一、sortedkey概述

sortedkey是Python中的一个排序函数,它主要用于从一个可迭代对象中提取关键字,并根据这些关键字进行排序。 在使用sortedkey函数时,需要指定一个key函数,这个函数用于从一个元素中提取排序所需的关键字,并作为排序的依据。 在Python中,sortedkey的使用非常广泛。由于Python的面向对象特性,通过在key函数中调用类的某个属性或方法,可以轻松地完成各种细致、复杂的排序需求。

二、sortedkey使用方法

sortedkey函数的基本使用方法如下:

sorted(iterable, key=key, reverse=reverse)

其中,iterable表示要排序的可迭代对象;key是一个函数,用来提取排序的关键字;reverse是一个布尔值,表示是否要倒序排序,默认为False。 下面是一个简单的例子:

numbers = [3, 5, 1, 2, 4]
sorted_numbers = sorted(numbers)
print(sorted_numbers)  # [1, 2, 3, 4, 5]
words = ['apple', 'banana', 'cherry', 'date']
sorted_words = sorted(words, key=len)
print(sorted_words)  # ['date', 'apple', 'banana', 'cherry']

在第二个例子中,我们通过指定key函数为len,实现了按照单词长度排序的功能。

三、sortedkey高级应用

3.1、按多个关键字排序

在实际开发中,我们常常需要根据多个关键字进行排序,可以通过传递一个元组作为key函数,实现按多个关键字排序。 下面是一个按照姓名、年龄、成绩进行排序的例子:

students = [
    {'name': 'Tom', 'age': 20, 'score': 90},
    {'name': 'Bob', 'age': 18, 'score': 98},
    {'name': 'Alice', 'age': 22, 'score': 85},
    {'name': 'Tim', 'age': 20, 'score': 95},
    {'name': 'John', 'age': 19, 'score': 85},
]
sorted_students = sorted(students, key=lambda x: (x['name'], x['age'], -x['score']))
print(sorted_students)
# [{'name': 'Alice', 'age': 22, 'score': 85},
#  {'name': 'Bob', 'age': 18, 'score': 98},
#  {'name': 'John', 'age': 19, 'score': 85},
#  {'name': 'Tim', 'age': 20, 'score': 95},
#  {'name': 'Tom', 'age': 20, 'score': 90}]

在这个例子中,我们首先按照姓名进行排序,如果姓名相同则按照年龄进行排序,如果年龄和姓名都相同则按照成绩逆序排序。

3.2、按字典顺序排序

在Python中,字典是一种非常常见的数据结构,我们有时会需要按照字典的顺序对字典进行排序。这时,可以通过调用字典的items方法,将字典转化为包含元组的列表,再传递给sorted函数进行排序。 下面是一个对字典按照键名字典序排序的例子:

d = {'banana': 3, 'apple': 2, 'cherry': 1}
sorted_d = sorted(d.items())
print(sorted_d)  # [('apple', 2), ('banana', 3), ('cherry', 1)]

3.3、按对象属性排序

在Python中,我们可以定义类来表示某种实体,而按照对象的某个属性进行排序是一个常见的需求。这时,可以通过在key函数中调用对象的属性或方法,实现按照对象属性排序的功能。 下面是一个按照人的年龄进行排序的例子:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    def __repr__(self):
        return f"{self.name}({self.age})"
persons = [Person('Tom', 20), Person('Bob', 18), Person('Alice', 22)]
sorted_persons = sorted(persons, key=lambda x: x.age)
print(sorted_persons)  # [Bob(18), Tom(20), Alice(22)]

3.4、按照自然排序排序

在默认情况下,sortedkey函数按照ASCII码的序列进行排序,比如'a'会排在'A'的前面。有时我们需要按照自然排序进行排序,比如1会排在10的前面,这时可以使用Python标准库中的natsort模块。 下面是一个按照自然排序进行排序的例子:

import natsort
items = ['a1', 'a10', 'a3', 'a2']
sorted_items = natsort.natsorted(items)
print(sorted_items)  # ['a1', 'a2', 'a3', 'a10']

3.5、使用sorted函数对对象列表排序

有时,我们需要对一个包含不同类型对象的列表进行排序,比如学生列表中包含了学生对象和其他非学生对象(如字符串、数字等),这时可以通过在key函数中使用isinstance函数,判断对象类型并进行不同的排序处理。 下面是一个对学生列表进行排序的例子,其中学生对象的关键字为姓氏、名字、年龄,非学生对象的关键字为值:

class Student:
    def __init__(self, first_name, last_name, age):
        self.first_name = first_name
        self.last_name = last_name
        self.age = age
    def __repr__(self):
        return f"{self.last_name} {self.first_name} ({self.age})"
items = [
    Student('Tom', 'Brown', 20),
    3,
    'apple',
    Student('Bob', 'Green', 18),
    5,
    'cherry',
    Student('Alice', 'Black', 22)
]
sorted_items = sorted(items, key=lambda x: (
    isinstance(x, Student),
    x.last_name,
    x.first_name,
    x.age if isinstance(x, Student) else x
))
print(sorted_items)
# [3,
#  5,
#  'apple',
#  'cherry',
#  Black Alice (22),
#  Green Bob (18),
#  Brown Tom (20)]

四、总结

本文详细介绍了Python中的排序函数sortedkey的使用方法和高级应用场景,并给出了相应的代码示例。在实际开发中,sortedkey是一个非常常用和强大的函数,能够轻松地完成各种排序需求。