How to sort a list of integers in descending order python

I've tried to figure it out in different ways, with no success. I keep getting ascending order instead of descending order when printing. In the meantime, there is no need to know about it. ”

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

      

+3


source to share


5 answers


You print the list sorted in ascending order:

print sorted(ListB)

      

If you want it to go down, put the print statement on the previous line (where you will undo it)

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

      



Then remove the final print instruction. In the meantime, there is no need to know about it. ”

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]

      

+8


source


Try this, it will sort the list in place in descending order (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]

      

+9


source


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

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

print ListB

      

Sorting does not change the variable passed to it. Therefore, if you want to do something with them, you need to store the sorted output into a variable.

+2


source


reversed(sorted(listb))

      

This creates an iterative jump from 48 -> -36

0


source


u had to concatenate these two lines of code together using that instead.

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

      

result:

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

      

0


source







All Articles