所以我是 python 的新手,我有一个项目需要我们通过一个非常长的元组列表,我们必须按降序和升序对列表进行排序。但是,对于我的两个功能,我总是按升序排列,怎么了?有人请帮助我真的很紧张
def bubblesort_descending(tuple_list):
j = len(tuple_list)
made_swap = True
swaps = 0
while made_swap:
made_swap = False
for cnt in range (j-1):
if tuple_list[cnt] < tuple_list[cnt+1]:
tuple_list[cnt], tuple_list[cnt+1] = tuple_list[cnt+1], tuple_list[cnt]
made_swap = True
swaps = swaps + 1
return swaps
主程序:
elif choice == 'd':
unsorted = range(len(numbers))
shuffle(unsorted)
print ("Randomised tuple list generated:")
print
print (unsorted)
swaps = bubblesort_descending (unsorted)
print
print ("heres the sorted list")
print
print (unsorted)
print
print (swaps, "swap(s) made")
print
最佳答案
升序和降序排序顺序的基本区别在于比较:这是一个冒泡排序实现取自 http://www.codecodex.com/wiki/Bubble_sort#Python :
def bubble_sort(lst, asc=True):
lst = list(lst) # copy collection to list
for passesLeft in range(len(lst)-1, 0, -1):
for i in range(passesLeft):
if asc:
if lst[i] > lst[i + 1]:
lst[i], lst[i + 1] = lst[i + 1], lst[i]
else:
if lst[i] < lst[i + 1]:
lst[i], lst[i + 1] = lst[i + 1], lst[i]
return lst
注意:区别基于asc
参数?
示例:
>>> xs = [1, 2, 9, 4, 0]
>>> bubble_sort(xs, asc=True)
[0, 1, 2, 4, 9]
>>> bubble_sort(xs, asc=False)
[9, 4, 2, 1, 0]
所以实际上交换了你的逻辑运算符 <
至 >
反转排序顺序。
关于python - python 中的冒泡排序帮助 - 升序和降序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21152778/