在 Python 中以降序对列表进行排序

Rayven Esplanada 2022年12月26日 Python Python List
在 Python 中以降序对列表进行排序

本教程演示了如何在 Python 中按降序对列表进行排序。

在 Python 中使用 sort() 方法以降序对列表进行排序

Python 具有称为 sort() 的内置函数,默认情况下,该函数以升序排列列表。此方法仅对给定列表的内容进行排序。它没有任何必需的参数,但具有可选参数:

  • key - 确定在多维数组内对哪个索引或位置进行排序。
  • reverse - 如果为 True,则列表以降序排列。

让我们看看该方法如何对有参数和无参数的列表进行排序:

  • 无参数:
colors = ["pink", "blue", "black", "white"]
colors.sort()

print(colors)

输出:

['black', 'blue', 'pink', 'white']

该列表根据字符串的 ASCII 值对字符串进行排序,这些字符串是单个字符的整数对应部分。如果比较中的两个字符串都具有相同的 ASCII 值,则它将继续比较两个字符串的下一个字符,直到没有可比较的内容为止。

  • 使用 reverse 参数:
colors = ["pink", "blue", "black", "white"]
colors.sort(reverse=True)
print(colors)

输出:

['white', 'pink', 'blue', 'black']

reverse 参数设置为 True 可以对列表进行降序排列。

排序整数和浮点数是根据数值大小进行排序。让我们用另一个例子试试,这次是按降序对整数和小数进行排序。

numbers = [55, 6, -0.05, 0.07, 2.5, -7, 2.99, 101, 0.78]
numbers.sort(reverse=True)

print(numbers)

输出:

[101, 55, 6, 2.99, 2.5, 0.78, 0.07, -0.05, -7]

从输出结果来看,使用 sort() 函数对数字进行排序时注意到了小数和负数。

这种类型的排序也适用于格式为 YYYY-MM-DD HH:MM:SS 的日期。让我们以时间戳列表为例来证明这一点。

timestamps = [
    "2021-04-15 09:08:30",
    "2021-04-14 08:09:38",
    "2021-04-18 12:10:52",
    "2021-04-21 23:39:22",
    "2021-04-13 14:40:22",
    "2021-04-14 13:59:46",
    "2021-04-15 19:22:37",
    "2021-04-18 07:00:58",
    "2021-04-17 04:01:50",
    "2021-04-22 01:17:13",
    "2021-04-25 24:22:13",
    "2021-04-14 25:36:38",
]

timestamps.sort(reverse=True)

print(timestamps)

输出:

['2021-04-25 24:22:13', '2021-04-22 01:17:13', '2021-04-21 23:39:22', '2021-04-18 12:10:52', '2021-04-18 07:00:58', '2021-04-17 04:01:50', '2021-04-15 19:22:37', '2021-04-15 09:08:30', '2021-04-14 25:36:38', '2021-04-14 13:59:46', '2021-04-14 08:09:38', '2021-04-13 14:40:22']

观察到输出已成功按降序排序,从而确认时间戳也可以通过将 sort() 函数与 reverse 参数一起使用进行正确排序。

总而言之,使用内置的 sort() 函数并将 reverse 参数设置为 True 可以按降序对 Python 列表进行排序。

Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
Rayven Esplanada avatar Rayven Esplanada avatar

Skilled in Python, Java, Spring Boot, AngularJS, and Agile Methodologies. Strong engineering professional with a passion for development and always seeking opportunities for personal and career growth. A Technical Writer writing about comprehensive how-to articles, environment set-ups, and technical walkthroughs. Specializes in writing Python, Java, Spring, and SQL articles.

LinkedIn

相关文章 - Python List