Sorting List in Descending Order in Python
In Python, sorting a list in descending order can be achieved using the sorted() function or the sort() method.
# using sorted() 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", ] sorted_timestamps = sorted(timestamps, reverse=True) print(sorted_timestamps)
This will create a new list with the elements sorted in descending order, leaving the original list unchanged.
To sort the list in-place, use the sort() method with reverse=True:
# using sort() timestamps.sort(reverse=True) print(timestamps)
For more details on sorting in Python, refer to the Sorting HOW TO documentation.
The above is the detailed content of How to Sort a List in Descending Order in Python?. For more information, please follow other related articles on the PHP Chinese website!