一尘不染

Python列表按降序排列

python

如何按降序对列表进行排序?

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

阅读 2561

收藏
2020-02-19

共2个答案

一尘不染

在一行中,使用lambda

timestamp.sort(key=lambda x: time.strptime(x, '%Y-%m-%d %H:%M:%S')[0:6], reverse=True)

将函数传递给list.sort

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

timestamp.sort(key=foo, reverse=True)
2020-02-19
一尘不染

这将为你提供阵列的排序版本。

sorted(timestamp, reverse=True)

如果要就地排序:

timestamp.sort(reverse=True)
2020-02-19