使用循环删除列表中不满足一定条件的元素



在读取列表' list '时,我想删除一个不满足特定条件的元素。基于以下答案:当从列表中删除项目而迭代时,结果很奇怪,我找到了一个非常有效的解决方案。以下是PyCharm中的代码:

for ind, el in enumerate(lst):
if not el.strip() or el.strip() != 'LABEL':
lst[ind] = None #  here I get a warning concerning ind
else:
break
lst = [n for n in lst if n is not None]

我不明白为什么我收到这个警告:

Unexpected type(s): (int, None) Possible type(s): (SupportsIndex, str) (slice, Iterable[str]) 
Inspection info:
Reports type errors in function call expressions, targets, and return values. In a dynamically typed language, this is possible in a limited number of cases.
Types of function parameters can be specified in docstrings or in Python 3 function annotations.

我们没有看到其余的代码,但您可能键入暗示您的lst只有str元素,而None不是str

你不需要实现2遍算法来删除元素。下面的代码应该等同于你的代码,没有警告(参见dropwhile的文档):

from itertools import dropwhile
lst = list(dropwhile(lambda el: el.strip() != 'LABEL', lst))

您可以使用列表推导并在一行中完成所有操作。请看下面的代码:

new_list = [x for x in lst if x.strip() != 'LABEL']

还有一件事,我不认为在循环遍历列表时修改它是个好主意。

最新更新