如何从列表中删除特定字词

  • 本文关键字:字词 删除 列表 python
  • 更新时间 :
  • 英文 :


我必须不同的单词列表,一个列表(非索引字)包含应从另一个列表(kafka)中排除的单词列表。

我试过了:

kafka.discard (stop) # this only works with sets and I do not want to transform my list into a set

有没有另一种方法可以从另一个列表中排除停止中的单词?

我正在使用python 3.4.0

既然你说你不想使用集合(为什么?),你可以使用列表推导

kafka[:] = [x for x in kafka if x not in stop]

编辑:请注意slice[:],此方法更接近于.discard()的行为,因为保留了收藏的身份。

你可以试试这个:

stopwords_set = set(stopwords)
kafka = [word for word in kafka if word not in stopwords_set]

kafka中删除stopwords列表中每个单词的一种方法是:

for word in stopwords:
    while word in kafka:
        kafka.remove(word)

最新更新