[英]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.
我不需要一些字符串,因为它是重复的 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).
我使用应该删除字符串的while循环定义了一个function,但是我需要多次运行单元格,因为while循环在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 :正如Sayse在评论中所说:
If you're deleting an index, you don't need to increment
i
since the next index will have moved to current position如果要删除索引,则不需要增加
i
因为下一个索引将移动到当前 position
ie 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:我会在这里建议一个
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
This can also be written as a list comprehension:这也可以写成列表推导:
new_list = [s for s in list_of_strings if s not in headers]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.