我正在制作一個名為“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
提交
取消