You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python自定义降序排序函数异常:负数无法正确排序问题排查

问题排查与修复

问题根源

你的myMax()函数中location的索引逻辑混乱,导致无法正确定位并删除当前最大值,最终出现重复元素:

  • 初始化时location=0(对应max_num的索引),但找到更大元素时却赋值为counter+1(变成从1开始的位置编号)
  • 当处理到只剩正数1和负数的阶段,max_num=1,后续负数都更小,location保持0,此时a_list.pop(location-1)等价于pop(-1),删除的是列表最后一个元素(而非索引0的1)
  • 1始终留在列表中,每次循环都被当作最大值添加,直到列表被清空,最终输出重复的1

另外,原代码中输入转换用int(i)会报错,因为输入包含浮点数4.5,需改为float(i)适配整数和浮点数。

修正后的代码

def myMax(a_list):
    max_num = a_list[0]
    location = 0  # 初始化为max_num的索引
    counter = 1
    list_size = len(a_list)
    while counter < list_size:
        if max_num < a_list[counter]:
            max_num = a_list[counter]
            location = counter  # 直接记录当前元素的索引,而非counter+1
        counter += 1
    return max_num, location

def mySort(a_list):
    list_size = len(a_list)
    counter = 0
    des_list = []
    while counter < list_size:
        max_num, location = myMax(a_list)
        des_list.append(max_num)
        a_list.pop(location)  # 直接用索引删除,无需减1
        counter += 1
    return des_list

input_list = input("Please enter a list of different numbers separated by ',' : ")
input_list = input_list.split(",")
input_list = [float(i) for i in input_list]  # 改为float适配整数和浮点数
print("The descending sorted list is {}.".format(mySort(input_list)))

测试验证

输入1,-3,4.5,5,18,-1,3,-4,输出为:
The descending sorted list is [18.0, 5.0, 4.5, 3.0, 1.0, -1.0, -3.0, -4.0].
与预期一致。

内容的提问来源于stack exchange,提问作者Hamza Ali

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 10:45:36