Python列表按降序排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4183506/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 14:40:07  来源:igfitidea点击:

Python list sort in descending order

pythonsortingreverse

提问by Rajeev

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

采纳答案by Ignacio Vazquez-Abrams

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)

回答by Marcelo Cantos

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)

回答by Russell Dias

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

回答by Wolph

You can simply do this:

你可以简单地这样做:

timestamp.sort(reverse=True)

回答by mostafa elmadany

you simple type:

你简单的类型:

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

回答by I_code

Here is another way

这是另一种方式


timestamp.sort()
timestamp.reverse()
print(timestamp)