簡體   English   中英

"如何按python降序對整數列表進行排序"

[英]How to sort integer list in python descending order

我試圖以不同的方式解決這個問題,但沒有成功。 我在打印時不斷得到升序排序,而不是降序排序。

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

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

print sorted(ListB)

如果您希望它降序,請將您的打印語句放在前一行(您將其反轉的位置)

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

然后刪除您的最終打印語句。

例子:

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

試試這個,它會按降序對列表進行就地排序(在這種情況下不需要指定鍵):

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]

或者,您可以創建一個新的排序列表:

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 不會改變傳遞給它的變量。 所以如果你想對它們做任何事情,你必須將排序的輸出存儲到一個變量中。

reversed(sorted(listb))

這將創建一個從 48 -> -36 開始的可迭代對象

你應該把這兩行代碼組合在一起,用這個來代替。

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

結果:

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

在 Python 中,您可以按如下方式排序:

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

這將是使用選擇排序的實際實現:

# 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])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM