欢迎访问宙启技术站
智能推送

sorted函数在Python中的应用示例

发布时间:2023-09-28 02:58:46

sorted函数在Python中是非常常用的一个内置函数,它可以对可迭代对象进行排序。下面是sorted函数在Python中的应用示例。

1. 对列表进行排序

numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5]
sorted_numbers = sorted(numbers)
print(sorted_numbers)  # 输出 [1, 1, 2, 3, 4, 5, 5, 6, 9]

上述代码中,我们定义了一个包含多个数字的列表numbers,然后使用sorted函数对该列表进行排序,并将排序后的结果赋值给变量sorted_numbers。最后将排序后的结果打印输出。

2. 对字符串进行排序

str = "hello world"
sorted_str = sorted(str)
print(sorted_str)  # 输出 [' ', 'd', 'e', 'h', 'l', 'l', 'l', 'o', 'o', 'r', 'w']

上述代码中,我们定义了一个包含多个字符的字符串str,然后使用sorted函数对该字符串进行排序,并将排序后的结果赋值给变量sorted_str。最后将排序后的结果打印输出。注意,字符串在被排序时是按照字符的ASCII码值进行排序的。

3. 对元组进行排序

tuple = (3, 1, 4, 1, 5, 9, 2, 6, 5)
sorted_tuple = sorted(tuple)
print(sorted_tuple)  # 输出 [1, 1, 2, 3, 4, 5, 5, 6, 9]

上述代码中,我们定义了一个包含多个数字的元组tuple,然后使用sorted函数对该元组进行排序,并将排序后的结果赋值给变量sorted_tuple。最后将排序后的结果打印输出。与列表一样,元组也可以使用sorted函数进行排序。

4. 对字典进行排序

scores = {"Alice": 90, "Bob": 80, "Cindy": 95, "David": 85}
sorted_scores = sorted(scores.items(), key=lambda x: x[1], reverse=True)
print(sorted_scores)  # 输出 [('Cindy', 95), ('Alice', 90), ('David', 85), ('Bob', 80)]

上述代码中,我们定义了一个字典scores,其中包含了不同学生的成绩。我们使用sorted函数对该字典进行排序,以成绩为排序关键字,并且设置reverse参数为True使得按降序排序。最后将排序后的结果打印输出。

5. 对自定义对象进行排序

class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __repr__(self):
        return f"Student(name='{self.name}', age={self.age})"

students = [Student("Alice", 20), Student("Bob", 18), Student("Cindy", 19)]
sorted_students = sorted(students, key=lambda s: s.age)
print(sorted_students)  # 输出 [Student(name='Bob', age=18), Student(name='Cindy', age=19), Student(name='Alice', age=20)]

上述代码中,我们定义了一个Student类,并且创建了多个Student对象。然后我们使用sorted函数对Student对象列表进行排序,以年龄为排序关键字,并且设置lambda函数作为key参数来指定排序规则。最后将排序后的结果打印输出。

以上是sorted函数在Python中的应用示例,通过sorted函数我们可以轻松地对列表、字符串、元组、字典以及自定义对象等进行排序,非常方便实用。