Python list sort in descending order

2019-01-01 00:21发布

How can I sort this list in descending order?

timestamp = [
    "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"
]

5条回答
呛了眼睛熬了心
2楼-- · 2019-01-01 00:59

you simple type:

timestamp.sort()
timestamp=timestamp[::-1]
查看更多
骚的不知所云
3楼-- · 2019-01-01 01:02

You can simply do this:

timestamp.sort(reverse=True)
查看更多
余欢
4楼-- · 2019-01-01 01:07

In one line, using a lambda:

timestamp.sort(key=lambda x: time.strptime(x, '%Y-%m-%d %H:%M:%S')[0:6], reverse=True)

Passing a function to list.sort:

def foo(x):
    return time.strptime(x, '%Y-%m-%d %H:%M:%S')[0:6]

timestamp.sort(key=foo, reverse=True)
查看更多
与君花间醉酒
5楼-- · 2019-01-01 01:10

This will give you a sorted version of the array.

sorted(timestamp, reverse=True)

If you want to sort in-place:

timestamp.sort(reverse=True)
查看更多
浮光初槿花落
6楼-- · 2019-01-01 01:13

Since your list is already in ascending order, we can simply reverse the list.

>>> timestamp.reverse()
>>> timestamp
['2010-04-20 10:25:38', 
'2010-04-20 10:12:13', 
'2010-04-20 10:12:13', 
'2010-04-20 10:11:50', 
'2010-04-20 10:10:58', 
'2010-04-20 10:10:37', 
'2010-04-20 10:09:46', 
'2010-04-20 10:08:22',
'2010-04-20 10:08:22', 
'2010-04-20 10:07:52', 
'2010-04-20 10:07:38', 
'2010-04-20 10:07:30']
查看更多
登录 后发表回答