Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python list sort in descending order

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"
]
like image 352
Rajeev Avatar asked Nov 15 '10 10:11

Rajeev


People also ask

How do you sort a list in descending order in Python?

Sort in Descending order The sort() method accepts a reverse parameter as an optional argument. Setting reverse = True sorts the list in the descending order.

How do you sort in descending order?

The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.

How do you check if a list is in descending order in Python?

Method #1 : Naive method The simplest way to check this is run a loop for first element and check if we could find any larger element than it after that element, if yes, the list is not reverse sorted. if ( not flag) : print ( "Yes, List is reverse sorted." )


6 Answers

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)

Check the docs at Sorting HOW TO

like image 65
Marcelo Cantos Avatar answered Oct 08 '22 04:10

Marcelo Cantos


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)
like image 43
Ignacio Vazquez-Abrams Avatar answered Oct 08 '22 04:10

Ignacio Vazquez-Abrams


You can simply do this:

timestamps.sort(reverse=True)
like image 24
Wolph Avatar answered Oct 08 '22 02:10

Wolph


you simple type:

timestamps.sort()
timestamps=timestamps[::-1]
like image 38
mostafa elmadany Avatar answered Oct 08 '22 03:10

mostafa elmadany


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']
like image 42
Russell Dias Avatar answered Oct 08 '22 04:10

Russell Dias


Here is another way


timestamps.sort()
timestamps.reverse()
print(timestamps)
like image 22
hamdan Avatar answered Oct 08 '22 04:10

hamdan