如何在Python中按降序对整数列表进行排序

21
我尝试了多种方法来解决这个问题,但都没有成功。当我打印时,我得到的是升序排序,而不是降序排序。
ListB = [24, 13, -15, -36, 8, 22, 48, 25, 46, -9]
sorted(ListB, key=int, reverse=True)
print sorted(ListB)

1
reversed(sorted(listb)) - Jakob Bowyer
2
你输入了 print sorted(ListB),这会自然地打印出已排序的 ListB - tckmn
相关链接:*按升序对数字字符串列表进行排序* - Peter Mortensen
7个回答

22

您正在按升序打印列表:

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]

14
试试这个。它会按降序原地对列表进行排序(在这种情况下不需要指定键):
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]

你的建议很不错,因为我最终会需要一个新列表。我正在通过手动创建一个箱线图来自学Python。对列表进行排序是很重要的。再次感谢! - Math4CT

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

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

print ListB

sorted不会改变传递给它的变量。因此,如果您想对它们进行任何操作,您必须将排序后的输出存储到一个变量中。


0
reversed(sorted(listb))

这将创建一个可迭代对象,从48到-36


只需使用reversed(ListB)即可。 - Edmund

0
你应该把这两行代码合并在一起,使用这个代替。
print sorted(ListB, key=int, reverse=True)

结果:

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

0
在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)

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

这应该可以工作


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接