亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Python 中的列表排序算法不運行

Python 中的列表排序算法不運行

jeck貓 2023-03-08 16:21:36
我正在制作一個名為“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



查看完整回答
反對 回復 2023-03-08
  • 1 回答
  • 0 關注
  • 145 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號