Python中的While循环在False之前停止

Python中的While循环在False之前停止,python,loops,while-loop,jupyter,Python,Loops,While Loop,Jupyter,我有一个字符串列表。我不需要一些字符串,因为它是一个重复的标题。 我使用while循环定义了一个函数,该函数应该删除字符串,但是当while循环在I=len(字符串列表)之前停止时,我需要多次运行该单元格。 如果我多次运行该单元,那么它最终会工作。 我做错了什么 def header_eraser(list_of_strings): i=0 while i < len(list_of_strings): if list_of_strings[i] in he

我有一个字符串列表。我不需要一些字符串,因为它是一个重复的标题。 我使用while循环定义了一个函数,该函数应该删除字符串,但是当while循环在I=len(字符串列表)之前停止时,我需要多次运行该单元格。 如果我多次运行该单元,那么它最终会工作。 我做错了什么

def header_eraser(list_of_strings):
    i=0
    while i < len(list_of_strings):
        if list_of_strings[i] in headers:
            del list_of_strings[i]
            i+=1
        else:
            i+=1
def header_橡皮擦(字符串列表):
i=0
而i
当您删除一个元素时,列表的长度会改变,因此您会跳过一些元素,这就是为什么如果您多次运行它,它会工作的原因

我建议在这里为循环设置一个
,这样您就不必担心NT索引了:

def header_eraser(list_of_strings):
    new_list = []
    for s in list_of_strings:
        if s not in headers:
            new_list.append(s)
    return new_list
这也可以写成一个列表:

new_list = [s for s in list_of_strings if s not in headers]
如中所述:


如果要删除索引,则不需要增加
i
,因为下一个索引将移动到当前位置

i、 e


如果要删除索引,则不需要增加
i
,因为下一个索引将移动到当前位置,您可能需要查看列表理解,因为在迭代时从列表中删除内容可能会非常麻烦。顺便说一下,我会从上一个列表中构建另一个列表,以避免在遍历列表时删除元素。看一看。@Sayse:啊,当然!!!!非常感谢,现在觉得自己够傻了。@MetallimaX,MitchellOlislagers非常感谢,会的。@Sayse你是对的:)我编辑了,对不起
def header_eraser(list_of_strings):
    i = 0
    while i < len(list_of_strings):
        if list_of_strings[i] in headers:
            del list_of_strings[i]
            # i += 1  # <- Remove this line
        else:
            i += 1
def header_eraser(list_of_strings):
    return [s for s in list_of_strings if s not in headers]