我正在制作一个名为“dumbstuff”的模块,只是出于一种爱好,似乎无法确定问题所在。该函数设置为接受一个列表和一个运算符,以按升序或降序对列表进行排序。当我运行该功能时,出现一个空白屏幕,我已经用了一段时间,但无法弄清楚出了什么问题。这是“dumbstuff”模块中的排序函数:def sortlist(rawlist: list, operator: str, ifprint: bool): looped = 0 done = 0 index = 0 sortedList = [] while (done == 0): index = 0 looped = 0 #ascending sort if (operator == "<"): while (index < len(rawlist) - 1): if (rawlist[index] > rawlist[index + 1]): temp = rawlist[index] rawlist[index] = rawlist[index + 1] rawlist[index + 1] = temp looped += 1 if (looped == 0): done = 1 sortedList = rawlist #descending sort if (operator == ">"): while (index < len(rawlist) - 1): if (rawlist[index] < rawlist[index + 1]): temp = rawlist[index + 1] rawlist[index + 1] = rawlist[index] rawlist[index] = temp looped += 1 if (looped == 0): done += 1 sortedList = rawlist if (ifprint == True): print(sortedList)这是我试图运行它的代码,它创建了一个包含 20 个随机整数的数组,import randomimport dumbstuff as dsarray = []index = 0while (index < 20): array.append(random.randint(0, 20)) index += 1ds.sortlist(array, "<", ifprint=True)input()但是,代码似乎永远不会返回,也永远不会向屏幕输出任何内容。
1 回答
紫衣仙女
TA贡献1839条经验 获得超15个赞
您需要index在代码中的某处增加。
或许您可以将 while 循环替换为 for 循环。
#ascending sort
if (operator == "<"):
for index in range(len(rawlist) - 1): # Here.
while (index < len(rawlist) - 1):
通过此更改,它似乎可以工作https://repl.it/repls/SilentDelectablePrinter。
添加回答
举报
0/150
提交
取消