如何依降序對 Python 清單進行排序?

Barbara Streisand
發布: 2024-11-14 20:26:02
原創
832 人瀏覽過

How to Sort Python Lists in Descending Order?

Sorting Python Lists in Descending Order

In Python, you may encounter scenarios where you need to organize a list of elements in descending order. This guide will provide you with two methods to achieve this and demonstrate their usage with an example.

Method 1: Using the sorted() Function

The sorted() function can be utilized to return a new sorted list while preserving the original list. To sort in descending order, simply specify the reverse=True parameter:

sorted_timestamps = sorted(timestamps, reverse=True)
登入後複製

This will generate a new list, sorted_timestamps, containing the timestamps in descending chronological order.

Method 2: Using the sort() Method

Alternatively, you can use the sort() method to modify the original list in-place. Similar to sorted(), you can pass reverse=True to sort in descending order:

timestamps.sort(reverse=True)
登入後複製

This will rearrange the timestamps list itself in descending order without creating a new copy.

Example

Consider the following list of timestamps:

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",
]
登入後複製

Using Method 1:

sorted_timestamps = sorted(timestamps, reverse=True)
print(sorted_timestamps)  # ['2010-04-20 10:25:38', '2010-04-20 10:12:13', ...]
登入後複製

Using Method 2:

timestamps.sort(reverse=True)
print(timestamps)  # ['2010-04-20 10:25:38', '2010-04-20 10:12:13', ...]
登入後複製

In both cases, the timestamps list will be sorted in descending order from the most recent to the oldest timestamp.

以上是如何依降序對 Python 清單進行排序?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板