简体   繁体   中英

While loop in Python stopping before False

I'm having a list of strings. I don't need some of the strings as it's a repeating header. I defined a function using while loop that should remove the strings, however I need to run the cell multiple times as the while loop stops before i=len(list_of_strings). If I run the cell multiple times, then it eventually works. What did I do wrong?

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

As Sayse said in a comment :

If you're deleting an index, you don't need to increment i since the next index will have moved to current 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

However, you might find it easier to use a list comprehension, which requires returning a new list instead of modifying the existing one:

def header_eraser(list_of_strings):
    return [s for s in list_of_strings if s not in headers]

When you remove an element, the length of the list changes and therefore you are skipping some elements, that's why if you run it multiple times it works.

I would suggest a for loop here, so you don't have to worry abount indexes:

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

This can also be written as a list comprehension:

new_list = [s for s in list_of_strings if s not in headers]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM