我有两个项目列表,每个项目都是一个字符串。我想绕过两个项目,如果不是一组单词中的一个单词,则基本上删除一个单词。但是,以下代码将所有单词放在一起,而不是创建两个单独的项目。我希望自己的updatedlist有两个项目,每个要更新的原始项目一个:
#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']
答案 0 :(得分:2)
如果您喜欢列表推导,可以使用以下示例:
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']]
答案 1 :(得分:1)
因此,如果我正确理解了您的问题,那么您想将列表追加到列表中。
这应该可以完成工作:
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)
答案 2 :(得分:1)
除了将所有文章的单词添加到一个列表中之外,您需要为每个文章维护单独的列表,最后将它们添加到updated_list
中。
答案 3 :(得分:1)
您可以执行以下操作:
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']]
但是我建议您使用以下data type precedence list,因为它被认为是更多 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']]