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

Python中的sorted函数用法及实例演示

发布时间:2023-10-28 03:53:25

Python中的sorted()函数是一个内置函数,用于对可迭代对象(例如列表,元组或集合)进行排序并返回一个新的已排序的列表。

sorted()函数有以下几种用法:

1. 对列表进行排序:可以将一个列表作为参数传递给sorted()函数,它将返回一个已排序的新列表。

   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]
   

请注意,sorted()函数不会修改原始列表,而是返回一个新的已排序列表。

2. 对字符串进行排序:sorted()函数也可以对字符串进行排序,它将返回一个按字母顺序排序的新字符串。

   string = "python"
   sorted_string = sorted(string)
   print(sorted_string)  # 输出:['h', 'n', 'o', 'p', 't', 'y']
   

注意,sorted()函数将字符串拆分为单个字符,然后按照字符的Unicode值进行排序。

3. 自定义排序规则:sorted()函数还允许使用关键字参数key来指定自定义的排序规则。key参数应该是一个函数,它接受一个元素作为输入并返回一个用于排序的键。例如,可以使用key参数按照字符串的长度对列表进行排序。

   words = ["apple", "banana", "cherry", "durian"]
   sorted_words = sorted(words, key=len)
   print(sorted_words)  # 输出:['apple', 'banana', 'cherry', 'durian']
   

在这个例子中,key参数传递了len函数,它返回字符串的长度作为排序的键。

4. 逆序排序:如果需要按照逆序进行排序,可以将关键字参数reverse设置为True。

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

在这个例子中,sorted()函数将按照降序对数字进行排序。

上述是sorted()函数的一些常见用法。下面将通过两个实例演示sorted()函数的使用。

实例1:按照学生成绩排序

假设有一个学生列表,每个学生的信息包括姓名和分数。需要按照分数从高到低对学生进行排序并输出排序后的学生列表。

students = [
    {"name": "Tom", "score": 87},
    {"name": "John", "score": 92},
    {"name": "Emily", "score": 78},
    {"name": "Sara", "score": 85}
]

sorted_students = sorted(students, key=lambda x: x["score"], reverse=True)
for student in sorted_students:
    print(student["name"], student["score"])

输出:

John 92
Tom 87
Sara 85
Emily 78

在这个例子中,sorted()函数使用了一个lambda函数作为key参数,该函数返回学生的分数作为排序的键,并设置reverse参数为True以实现降序排序。

实例2:按照年龄和姓名排序

在这个例子中,有一个人员列表,每个人的信息包括姓名和年龄。需要首先按照年龄排序,然后按照姓名排序,并输出排序后的人员列表。

people = [
    {"name": "Tom", "age": 25},
    {"name": "John", "age": 22},
    {"name": "Emily", "age": 27},
    {"name": "Sara", "age": 23}
]

sorted_people = sorted(people, key=lambda x: (x["age"], x["name"]))
for person in sorted_people:
    print(person["name"], person["age"])

输出:

John 22
Sara 23
Tom 25
Emily 27

在这个例子中,sorted()函数的key参数是一个lambda函数,它将年龄和姓名组成的元组作为排序的键。这样,首先按照年龄进行排序,然后在相同年龄的人中按照姓名进行排序。

这是对sorted()函数的用法及实例演示的总结。sorted()函数在排序时非常实用,并且可以与各种数据类型一起使用。在处理排序需求时,可以考虑使用sorted()函数。