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

如何使用sorted函数按升序或降序对Python列表进行排序?

发布时间:2023-06-26 08:16:44

sorted函数是Python中用于排序序列和列表的内置函数,它接受一个可迭代对象作为参数,并返回一个新的已排序的列表。sorted函数可以按升序或降序排列\Python列表。下面我们将讨论如何使用sorted函数进行列表排序。

1.按升序排序

要按升序对Python列表进行排序,可以使用sorted()函数,并将需要排序的列表作为函数的输入参数,如下所示:

numbers = [1, 9, 2, 8, 3, 7, 4, 6, 5]
sorted_numbers = sorted(numbers)
print(sorted_numbers)

输出将是:

[1, 2, 3, 4, 5, 6, 7, 8, 9]

sorted函数默认按升序排序,可以在sorted()函数中使用reverse=False来明确指定按升序排序。

numbers = [1, 9, 2, 8, 3, 7, 4, 6, 5]
sorted_numbers = sorted(numbers, reverse=False)
print(sorted_numbers) 

输出将是:

[1, 2, 3, 4, 5, 6, 7, 8, 9]

2.按降序排序

要按降序对Python列表进行排序,可以使用sorted()函数,并将列表作为输入参数。再使用reverse=True参数,如下所示:

numbers = [1, 9, 2, 8, 3, 7, 4, 6, 5]
sorted_numbers = sorted(numbers, reverse=True)
print(sorted_numbers)

输出将是:

[9, 8, 7, 6, 5, 4, 3, 2, 1]

sorted()函数中指定reverse=True,即可按降序对Python列表进行排序。

numbers = [1, 9, 2, 8, 3, 7, 4, 6, 5]
sorted_numbers = sorted(numbers, reverse=True)
print(sorted_numbers)

输出将是:

[9, 8, 7, 6, 5, 4, 3, 2, 1]

3. 字符串排序

可以将字符串存储到Python列表中,sorted函数可以按字母顺序对列表中的字符串进行排序。如下所示:

names = ['Tom', 'Jerry', 'Mickey', 'Goofy', 'Scooby']
sorted_names = sorted(names)
print(sorted_names)

输出将是:

['Goofy', 'Jerry', 'Mickey', 'Scooby', 'Tom']

根据Python字符串排序的ASCII值表,总体而言,大写字母排在前面,小写字母排在后面。根据这个顺序,sorted函数在对列表进行排序时,将按字符串的ASCII值表顺序对字符串进行排序。

4.自定义排序函数

当排序需要根据列表中的特定属性或条件进行排序时,可以使用自定义排序函数。sorted函数中可以指定关键字参数key。该参数接收一个函数,该函数用于指定将在排序中使用的属性或条件。

例如,在下面的列表中,如果需要根据列表中元组的第二个元素对其进行排序,则可以使用自定义函数来指定排序方式,如下所示:

students = [('Tom', 21), ('Jerry', 19), ('Mickey', 20), ('Goofy', 18), ('Scooby', 22)]
def sort_by_age(elem):
    return elem[1]
sorted_students = sorted(students, key=sort_by_age)
print(sorted_students)

输出将是:

[('Goofy', 18), ('Jerry', 19), ('Mickey', 20), ('Tom', 21), ('Scooby', 22)]

在这个示例中,我们定义了一个名为sort_by_age()的函数,该函数将列表中的元素的第二个元素作为排序的关键字。我们在sorted()函数调用中使用这个函数来指定自定义排序方式。