如何按降序对此列表进行排序?
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"
]
答案 0 :(得分:344)
在一行中,使用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)
答案 1 :(得分:342)
这将为您提供数组的排序版本。
sorted(timestamp, reverse=True)
如果您想就地排序:
timestamp.sort(reverse=True)
答案 2 :(得分:50)
你可以这样做:
timestamp.sort(reverse=True)
答案 3 :(得分:7)
由于您的列表已按升序排列,我们可以简单地撤消列表。
>>> 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']
答案 4 :(得分:5)
你简单的类型:
timestamp.sort()
timestamp=timestamp[::-1]
答案 5 :(得分:1)
这是另一种方式
timestamps.sort()
timestamps.reverse()
print(timestamps)