簡體   English   中英

Python 中的循環在 False 之前停止

[英]While loop in Python stopping before False

我有一個字符串列表。 我不需要一些字符串,因為它是重復的 header。 我使用應該刪除字符串的while循環定義了一個function,但是我需要多次運行單元格,因為while循環在i = len(list_of_strings)之前停止。 如果我多次運行該單元,那么它最終會起作用。 我做錯了什么?

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

正如Sayse評論中所說:

如果要刪除索引,則不需要增加i因為下一個索引將移動到當前 position

IE

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]

當您刪除一個元素時,列表的長度會發生變化,因此您會跳過一些元素,這就是為什么如果您多次運行它會起作用的原因。

我會在這里建議一個for循環,所以你不必擔心索引:

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]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM