Python 以相反的顺序对列表进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43432675/
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
Sort a list in reverse order
提问by m0_as
I have a list a = ['L', 'N', 'D']. I want to reverse the order of elements in a and get b = ['D', 'N', 'L']. I tried this:
我有一个列表 a = ['L', 'N', 'D']。我想反转 a 中元素的顺序并得到 b = ['D', 'N', 'L']。我试过这个:
a = ['L', 'N', 'D']
b = sorted(a, reverse=True)
But the output is
但输出是
b= ['N', 'L', 'D']
Where do I make a mistake?
我在哪里犯了错误?
回答by Rory Daulton
Your mistake is using sorted
, which rearranges the list in order of the elements and ignores where the elements used to be. Instead use
您的错误是使用sorted
,它按元素的顺序重新排列列表并忽略元素曾经所在的位置。而是使用
b = a[::-1]
That runs through list a
in reverse order. You also could use
a
以相反的顺序遍历列表。你也可以使用
b = list(reversed(a))
although the first version is faster.
虽然第一个版本更快。
回答by masnun
You can also reverse in place:
您也可以原地反转:
>>> a = ['L', 'N', 'D']
>>> a.reverse()
>>> a
['D', 'N', 'L']
But please note it changes the list, doesn't create (return) a new one.
但请注意,它会更改列表,不会创建(返回)新列表。
回答by bloodrootfc
If you want to use sorted(), you can specify that the index is the key to sort on:
如果你想使用 sorted(),你可以指定索引是排序的关键:
b = sorted(a, key=a.index, reverse=True)
回答by CharlieX
You had it almost right the first time. Try this:
你第一次就几乎是对的。尝试这个:
#This will sort the list temporarily into reverse alphabetical order.
print(sorted(a, reverse=True)
#This will sort the list temporarily into reverse order.
print(sorted(a, reverse=False)