这是我目前拥有的:
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循环内的可以让我确切地获得控制台中所需的内容(作为不同的字符串),但是我无法将其作为List或variable返回。我该怎么办?
答案 0 :(得分:3)
您的output=[]
在for循环内。因此,在每次迭代中,其值都会重新初始化,您应该在for循环之前使用output=[]
重试
答案 1 :(得分:1)
您返回的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)