sorting – Python list sort in descending order

The Question :

357 people think this question is useful

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"
]

The Question Comments :

The Answer 1

402 people think this answer is useful

In one line, using a lambda:

timestamps.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]

timestamps.sort(key=foo, reverse=True)

The Answer 2

409 people think this answer is useful

This will give you a sorted version of the array.

sorted(timestamps, reverse=True)

If you want to sort in-place:

timestamps.sort(reverse=True)

The Answer 3

60 people think this answer is useful

You can simply do this:

timestamps.sort(reverse=True)

The Answer 4

10 people think this answer is useful

you simple type:

timestamps.sort()
timestamps=timestamps[::-1]

The Answer 5

10 people think this answer is useful

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

>>> timestamps.reverse()
>>> timestamps
['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']

The Answer 6

1 people think this answer is useful

Here is another way


timestamps.sort()
timestamps.reverse()
print(timestamps)

Add a Comment