Python 戴尔似乎没有从列表中删除任何内容
这是我的密码。Word中的数据是元组列表,其中元组如下所示:Python 戴尔似乎没有从列表中删除任何内容,python,stop-words,Python,Stop Words,这是我的密码。Word中的数据是元组列表,其中元组如下所示: for x,y in words: for z in x: if z in stopwords: del x[x.index(z)] 我的代码的目的是从单词列表中删除所有stopwords。 唯一的问题是,停止字之后不会被删除 我到底做错了什么? 我已经试过了 (list of words, metadata) 但这似乎没有什么区别。您可以使用嵌套列表创建一个新列表,而不使用停止词:
for x,y in words:
for z in x:
if z in stopwords:
del x[x.index(z)]
我的代码的目的是从单词列表中删除所有stopwords。
唯一的问题是,停止字之后不会被删除
我到底做错了什么?
我已经试过了
(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]
请注意,通常不应修改正在迭代的列表。这可能会导致很多难以追踪的bug
>>> 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')]
最外层的循环将x
分配给一个单词列表。我们暂时忽略y
。第二个循环迭代该单词列表。它可能会跳过特定的单词。这适用于所有del、pop、移除和切片更换
确保stopwords
是一个set
并基于它过滤每个单词将更有效:x[:]=[w对于x中的w,如果w不在stopwords中]
。这里的切片替换纯粹是为了确保x
保持相同的对象,在这种情况下,确保words
中的条目发生更改。
这不会遇到前面提到的迭代问题,因为列表理解会在分配将列表存储到切片之前构建它的列表 在遍历时从列表中删除数据不是一个好主意,很可能会产生未定义的行为。相反,我会尝试将你的问题表述为一个列表理解,并创建一个符合你标准的新列表。请给出一个单词和停止词的示例,你能解释一下为什么创建一组停止词吗?我不理解这样的评论:对于集合,成员资格测试的(平均)渐近运行时间是
O(1)
,对于列表和元组等其他容器,则是O(n)
(另请参见)。特别是因为中的检查是在内部循环中完成的,因此潜在的节省可能是巨大的。
for x,y in words:
for z in x:
if z in stopwords:
del x[x.index(z)]