Python:for循环,包括循环外的行
我正在使用for循环创建一个多行字符串。循环完成后,我想调用一个弹出窗口并显示字符串。出于某种原因,它在每次迭代时都会调用弹出窗口,即使调用在For循环之后,并且缩进正确。我在网上找不到类似的东西。有什么想法吗Python:for循环,包括循环外的行,python,for-loop,iteration,Python,For Loop,Iteration,我正在使用for循环创建一个多行字符串。循环完成后,我想调用一个弹出窗口并显示字符串。出于某种原因,它在每次迭代时都会调用弹出窗口,即使调用在For循环之后,并且缩进正确。我在网上找不到类似的东西。有什么想法吗 string = "" for color in highlight_report_dict: if highlight_report_dict[color] == []: continue else: string += '{}\n'.f
string = ""
for color in highlight_report_dict:
if highlight_report_dict[color] == []:
continue
else:
string += '{}\n'.format(color)
for item in highlight_report_dict[color]:
start = str(int(float(item[0])))+'.0' #changes '3.34' to '3.0', etc for any index
end = str(int(float(item[1])))+'.0'
start = index_key[start]
end = index_key[end]
string += '{} - {}\n'.format(start, end)
print string #Why does it call popup() during for loop???
popup(string)
我期望的输出类似于:
“蓝色
1.4-2.5
黄色的
2.6-3.1“
但我得到的是:
“蓝色
1.4-2.5
蓝色的
1.4-2.5
黄色的
2.6-3.1“
如果需要,以下是整个功能:
def highlight_report():
tag_list = t.tag_names()[1:] #creates list of all highlight tag colors, removing 'ins' tag
start = '1.0'
end = t.index(END)
highlight_report_dict = {}
for color in tag_list:
highlight_report_dict[color] = []
cycle = True
while cycle:
highlight_report_dict[color].append(t.tag_nextrange(color, start, end))
try:
start = highlight_report_dict[color][-1][1] #uses previous tag end as new start
except IndexError:
start = '1.0'
cycle = False
if highlight_report_dict[color][-1] == (): #removes empty tuple created at end of cycle
del highlight_report_dict[color][-1]
string = ""
for color in highlight_report_dict:
if highlight_report_dict[color] == []:
continue
else:
string += '{}\n'.format(color)
for item in highlight_report_dict[color]:
start = str(int(float(item[0])))+'.0' #changes '3.34' to '3.0', etc for any index
end = str(int(float(item[1])))+'.0'
start = index_key[start]
end = index_key[end]
string += '{} - {}\n'.format(start, end)
print string #Why does it call popup() during for loop???
popup(string)
我明白了。这是一个制表符对四个空格的问题。我从一个编辑器中复制文本,使其升华。有些文本是选项卡式的,有些是四个空格。我已经将所有制表符转换为四个空格,现在我的for循环按预期工作。这是极不寻常的。尝试在for循环的最后一行和“打印字符串”之间插入换行符。再次检查所有缩进。解释器有时会出错。您是否尝试在没有弹出窗口(字符串)的情况下运行此解释器?是否可以编辑您的问题以显示缩进?您可能在for循环中调用它或其他什么。请发布一个。您的代码实际上引发了一个异常,并且似乎太长了。@manglano:我已经尝试按照您的建议插入一个换行符,但它并没有改变结果。