Python列表降序排序

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

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"
]
791687 次浏览

这将为您提供一个排序版本的数组。

sorted(timestamps, reverse=True)

如果你想就地排序:

timestamps.sort(reverse=True)

检查如何分类的文档

由于您的列表已经是升序的,我们可以简单地反转列表。

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

在一行中,使用lambda:

timestamps.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]


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

你可以简单地这样做:

timestamps.sort(reverse=True)

你简单的类型:

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

这是另一种方法


timestamps.sort()
timestamps.reverse()
print(timestamps)