如何按python降序对整数列表进行排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25374190/
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 20:07:45  来源:igfitidea点击:

How to sort integer list in python descending order

pythonlist

提问by Math4CT

I have tried to figure this out in different ways, to no success. I keep getting ascending order sort, rather than descending order when I print.

我试图以不同的方式解决这个问题,但没有成功。当我打印时,我一直在进行升序排序,而不是降序排序。

ListB = [24, 13, -15, -36, 8, 22, 48, 25, 46, -9]
sorted(ListB, key=int, reverse=True)
print sorted(ListB)

采纳答案by Andy

You are printing the list sorted ascending:

您正在打印按升序排序的列表:

print sorted(ListB)

If you want it descending, put your print statement on the previous line (where you reverse it)

如果您希望它降序,请将您的打印语句放在前一行(您将其反转的位置)

print sorted(ListB, key=int, reverse=True)

Then remove your final print statement.

然后删除您的最终打印语句。

Example:

例子:

>>> ListB = [24, 13, -15, -36, 8, 22, 48, 25, 46, -9]
>>> print sorted(ListB, key=int, reverse=True)
[48, 46, 25, 24, 22, 13, 8, -9, -15, -36]

回答by Jakob Bowyer

reversed(sorted(listb))

This creates an iterable going from 48 -> -36

这将创建一个从 48 -> -36 开始的可迭代对象

回答by óscar López

Try this, it'll sort the list in-place in descending order (there's no need to specify a key in this case):

试试这个,它会按降序对列表进行就地排序(在这种情况下不需要指定键):

listB = [24, 13, -15, -36, 8, 22, 48, 25, 46, -9]
listB.sort(reverse=True) # listB gets modified

print listB
=> [48, 46, 25, 24, 22, 13, 8, -9, -15, -36]

Alternatively, you can create a new sorted list:

或者,您可以创建一个新的排序列表:

listB = [24, 13, -15, -36, 8, 22, 48, 25, 46, -9]
listC = sorted(listB, reverse=True) # listB remains untouched

print listC
=> [48, 46, 25, 24, 22, 13, 8, -9, -15, -36]

回答by SimplyMagisterial

ListB = [24, 13, -15, -36, 8, 22, 48, 25, 46, -9]

ListB = sorted(ListB, key=int, reverse=True)

print ListB

Sorted does not change the variable passed to it. So if you want to do anything with them you have to store sorted output into a variable.

Sorted 不会改变传递给它的变量。所以如果你想对它们做任何事情,你必须将排序的输出存储到一个变量中。

回答by Andy

u should have combined these two lines of code together, using this instead.

你应该把这两行代码组合在一起,用这个来代替。

print sorted(ListB, key=int, reverse=True)

result:

结果:

[48, 46, 25, 24, 22, 13, 8, -9, -15, -36]