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

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

為什么這個 for 循環返回一個空列表?

為什么這個 for 循環返回一個空列表?

喵喵時光機 2023-12-08 17:16:44
這就是我目前擁有的:messages = {  "Placeholder": 0,  "1": 48,  "2": 4,  "3": 31,  "4": 2}def pls():    messages_sorted = sorted(messages, key=messages.get, reverse=True)    for i in range(10):        output = []        try:            currp = str(messages_sorted[i])            if currp == "Placeholder":                print("PLACEHOLDER DETECTED")                return output            currpp = messages[currp]            output.append(f"{currp} has {currpp} and is Place {i+1}")            print(output)        except IndexError:            print("Index error")        except:            print("some other error")        return outputoutput = pls()output = str(output)output = output.replace("['", "")output = output.replace("']", "")print(output)我已經使用這個問題的答案將不同的輸出制作為一個列表,但是當我運行它時,它返回一個空列表。當我刪除以下部分時:if currp == "Placeholder":            print("PLACEHOLDER DETECTED")            return output我剛剛收到一堆索引錯誤。這print(output)在 for 循環內部,我得到了控制臺中所需的內容(作為不同的字符串),但是我無法將其作為 List 或變量返回。我怎樣才能做到這一點?
查看完整描述

2 回答

?
白板的微信

TA貢獻1883條經驗 獲得超3個贊

output=[]在你的for循環里面。output=[]因此,在每次迭代時,它的值都會重新初始化,您應該在 for 循環之前重試



查看完整回答
反對 回復 2023-12-08
?
慕桂英3389331

TA貢獻2036條經驗 獲得超8個贊

當您返回時,您的output列表是空的,因為每次for loop重新啟動時都會重置列表。


您的代碼應如下所示:


  messages = {

  "Placeholder": 0,

  "1": 48,

  "2": 4,

  "3": 31,

  "4": 2

             }


def pls():

    messages_sorted = sorted(messages, key=messages.get, reverse=True)

    output = []

    for i in range(10):

        

        try:

            currp = str(messages_sorted[i])

            if currp == "Placeholder":

                print("PLACEHOLDER DETECTED")

                return output

            currpp = messages[currp]

            output.append(f"{currp} has {currpp} and is Place {i+1}")

            print(output)


        except IndexError:

            print("Index error")


        except:

            print("some other error")

    

    return output


output = pls()

output = str(output)

output = output.replace("['", "")

output = output.replace("']", "")

print(output)


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

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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