Python:for循环包括循环外的行

时间:2016-04-05 17:12:56

标签: python for-loop iteration

我使用for循环创建一个多行字符串。循环完成后,我想调用一个弹出窗口并显示字符串。由于某种原因,它会在每次迭代时调用弹出窗口,即使调用在for循环之后,也会正确缩进。我在网上找不到这样的东西。有什么想法吗?

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)

1 个答案:

答案 0 :(得分:0)

想出来。这是一个选项卡与四个空格问题。我将文本从一个编辑器复制到Sublime Text。一些文本是标签,一些是四个空格。我将Sublime转换为四个空格,现在我的for循环按预期工作。