我有一个包含两项的列表,每一项都是一串文本。我想循环这两个项目并基本上删除一个不在一组单词中的单词。然而,以下代码将所有单词放在一起,而不是创建两个单独的项目。我希望我的 updated_list 有两个项目,一个用于我正在更新的每个原始项目:
#stopwords is a variable for a set of words that I dont want in my final updated list
updated_list = []
articles = list_of_articles
for article in articles:
for word in article:
if word not in stopwords:
updated_list.append(word)
articles = [['this, 'is', 'a', 'test'], ['what', 'is', 'your', 'name']]
stopwords = {'is', 'a'}
expected output:
updated_list = [['this, 'test'],['what', 'your', 'name']]
current output:
updated_list = ['this, 'test','what', 'your', 'name']
请您参考如下方法:
如果你更喜欢列表理解,你可以使用这个例子:
articles = [['this', 'is', 'a', 'test'], ['what', 'is', 'your', 'name']]
stopwords = {'is', 'a'}
articles = [[word for word in article if word not in stopwords] for article in articles]
print(articles)
打印:
[['this', 'test'], ['what', 'your', 'name']]
