Python列表按降序排列

本文翻譯自:Python list sort in descending order

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

#1樓

參考:https://stackoom.com/question/HYJu/Python列表按降序排列


#2樓

you simple type: 您簡單的輸入:

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

#3樓

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)

#4樓

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

#5樓

In one line, using a lambda : 在一行中,使用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 : 將函數傳遞給list.sort

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

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

#6樓

您可以簡單地做到這一點:

timestamp.sort(reverse=True)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章