简体   繁体   中英

How to sort integer list in python descending order

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)

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]

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

reversed(sorted(listb))

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

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]

In Python you can sort as follows:

listA = [150, 120, 100, 165, 190, 145, 182, 175, 17]
print(sorted(listA))
print(sorted(listA, reverse=True))

This would be the actual implementation using selection sort:

# Traverse through all array elements
for i in range(len(listA)):

    # Find the minimum element in remaining
    # unsorted array
    min_idx = i
    for j in range(i + 1, len(listA)):
        if listA[min_idx] > listA[j]:
            min_idx = j

    # Swap the found minimum element with
    # the first element
    listA[i], listA[min_idx] = listA[min_idx], listA[i]

print(listA)

# Traverse through all array elements
for i in range(len(listA)):

    # Find the minimum element in remaining
    # unsorted array
    min_idx = i
    for j in range(i + 1, len(listA)):
        if listA[min_idx] < listA[j]:
            min_idx = j

    # Swap the found minimum element with
    # the first element
    listA[i], listA[min_idx] = listA[min_idx], listA[i]

print(listA)
ListB = [24, 13, -15, -36, 8, 22, 48, 25, 46, -9]
ListB.sort()
print(ListB[::-1])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM