为什么这个forloop返回一个空列表?

2024-09-30 12:15:13 发布

您现在位置:Python中文网/ 问答频道 /正文

这就是我目前拥有的:

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 output

output = pls()
output = str(output)
output = output.replace("['", "")
output = output.replace("']", "")
print(output)

我已经使用了this question的答案将不同的输出设置为一个列表,但是当我运行它时,它返回一个空列表。当我移除以下部分时:

if currp == "Placeholder":
            print("PLACEHOLDER DETECTED")
            return output

我只是得到了一堆索引错误。

print(output)

在for循环中,我得到了控制台中所需的内容(作为不同的字符串),但是我无法将其作为列表或变量返回。我该怎么做


Tags: 列表foroutputreturnifplaceholdermessagessorted
2条回答

返回时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)

您的output=[]在for循环中。因此,在每次迭代时,它的值都会重新初始化,您应该在for循环之前使用output=[]重试

相关问题 更多 >

    热门问题