[英]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. Sorted 不会改变传递给它的变量。 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:在 Python 中,您可以按如下方式排序:
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])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.