2 回答

TA貢獻1883條經(jīng)驗 獲得超3個贊
你output=[]
在你的for循環(huán)里面。output=[]
因此,在每次迭代時,它的值都會重新初始化,您應(yīng)該在 for 循環(huán)之前重試

TA貢獻2036條經(jīng)驗 獲得超8個贊
當(dāng)您返回時,您的output列表是空的,因為每次for loop重新啟動時都會重置列表。
您的代碼應(yīng)如下所示:
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)
添加回答
舉報