本文翻译自: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)