在 for 循环中附加列表

Appending list inside a for loop

我有一个包含两项的列表,每一项都是一串文本。我想循环这两个项目并基本上删除一个不在一组单词中的单词。然而,以下代码将所有单词放在一起,而不是创建两个单独的项目。我希望我的 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']

如果我正确理解你的问题,你想将列表附加到你的列表中。

这应该可以完成工作:

updated_list = []
articles = list_of_articles

for article in articles:
    temp_list = list()
    for word in article:
         if word not in stopwords:
             temp_list.append(word)
    updated_list.append(temp_list)

不是将所有文章的单词添加到一个列表中,而是需要为每篇文章维护单独的列表,最后将它们添加到 updated_list

您可以执行以下操作:

updated_list = []
stopwords = {'is', 'a'}

articles = [['this', 'is', 'a', 'test'], ['what', 'is', 'your', 'name']]

for article in articles:
    lst = []
    for word in article:
        if word not in stopwords:
            lst.append(word)
    updated_list.append(lst)

print(updated_list)

输出

[['this', 'test'], ['what', 'your', 'name']]

但是我建议你使用下面的nested list comprehension,因为它被认为更pythonic:

stopwords = {'is', 'a'}
articles = [['this', 'is', 'a', 'test'], ['what', 'is', 'your', 'name']]

updated_list = [[word for word in article if word not in stopwords] for article in articles]
print(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']]