Python列表按降序排序
如何按降序排列此列表?
timestamps = [
"2010-04-20 10:07:30",
"2010-04-20 10:07:38",
"2010-04-20 10:07:52",
"2010-04-20 10:08:22",
"2010-04-20 10:08:22",
"2010-04-20 10:09:46",
"2010-04-20 10:10:37",
"2010-04-20 10:10:58",
"2010-04-20 10:11:50",
"2010-04-20 10:12:13",
"2010-04-20 10:12:13",
"2010-04-20 10:25:38"
]
How can I sort this list in descending order?
timestamps = [
"2010-04-20 10:07:30",
"2010-04-20 10:07:38",
"2010-04-20 10:07:52",
"2010-04-20 10:08:22",
"2010-04-20 10:08:22",
"2010-04-20 10:09:46",
"2010-04-20 10:10:37",
"2010-04-20 10:10:58",
"2010-04-20 10:11:50",
"2010-04-20 10:12:13",
"2010-04-20 10:12:13",
"2010-04-20 10:25:38"
]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
这将为您提供数组的排序版本。
如果您想就地排序:
请查看文档 排序方法
This will give you a sorted version of the array.
If you want to sort in-place:
Check the docs at Sorting HOW TO
在一行中,使用 lambda :
将函数传递给 list.sort :
In one line, using a
lambda
:Passing a function to
list.sort
:你可以简单地这样做:
You can simply do this:
你简单的输入:
you simple type:
由于您的列表已经按升序排列,因此我们可以简单地反转列表。
Since your list is already in ascending order, we can simply reverse the list.
这是另一种方式
Here is another way
特别是如果数据是数字的话,可以使用否定来按降序排序。如果您无论如何都需要传递排序键,这尤其有用。例如,如果数据如下:
对于日期时间的示例,则如下所示:
Especially if the data is numeric, negation can be used to sort in descending order. This is especially useful if you need to pass a sorting key anyway. For example, if the data was as follows:
For an example with datetime, that would look like as follows: