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