关于排序:Python列表按降序排序

Python list sort in descending order

如何按降序排列此列表?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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"
]

在一行中,使用lambda

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

list.sort传递函数:

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

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


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

1
sorted(timestamp, reverse=True)

如果要就地排序:

1
timestamp.sort(reverse=True)


您只需执行以下操作:

1
timestamp.sort(reverse=True)


因为您的列表已经按升序排列,所以我们可以简单地反转列表。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
>>> 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']

简单类型:

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