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 to share
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 to share