[英]Python list sort in descending order
如何按降序對這個列表進行排序?
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"
]
這將為您提供數組的排序版本。
sorted(timestamps, reverse=True)
如果要就地排序:
timestamps.sort(reverse=True)
在一行中,使用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.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']
這是另一種方式
timestamps.sort()
timestamps.reverse()
print(timestamps)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.