del 似乎没有从列表中删除任何东西

del doesnt seem to delete anything from a list

for x,y in words:
    for z in x:
        if z in stopwords:
            del x[x.index(z)]

这是我的代码。 words 中的数据是一个元组列表,其中一个元组如下所示:

(list of words, metadata)

我的代码的目的是从单词列表中删除所有停用词。 唯一的问题是,之后没有删除停用词...

我到底做错了什么? 我已经尝试使用

x.pop(x.index(z))

但这似乎没有什么不同。

您可以使用嵌套列表理解简单地创建一个没有停用词的新列表:

stopwords = set(stopwords)  # just so "in" checks are faster
result = [([word for word in x if word not in stopwords], y) for x, y in words]

例如:

>>> stopwords = ['stop']
>>> words = [(['hello', 'you', 'stop'], 'somemeta')]
>>> stopwords = set(stopwords)  # just so "in" checks are faster
>>> result = [([word for word in x if word not in stopwords], y) for x, y in words]
>>> result
[(['hello', 'you'], 'somemeta')]

请注意,您通常不应修改正在迭代的列表。这可能会导致很多难以追踪的错误。

for x,y in words:
    for z in x:
        if z in stopwords:
            del x[x.index(z)]

最外层的循环将 x 分配给您的一个单词列表。我们暂时忽略 y。第二个循环遍历该单词列表; removing elements from a list you're iterating over causes peculiar behaviour。它可能会跳过特定的单词。这适用于所有的 del、pop、remove 和 slice 替换。

确保 stopwords 是一个 set 并根据它过滤每个单词会更有效:x[:] = [w for w in x if w not in stopwords] 而不是那个内部循环。这里的切片替换纯粹是为了确保 x 保持相同的对象,在这种情况下确保 words 中的条目发生变化。 这不会 运行 进入提到的迭代问题,因为列表理解在赋值将其存储到切片之前构建其列表。