gpt4 book ai didi

python - 在 for 循环中 append 列表

转载 作者:太空宇宙 更新时间:2023-11-04 08:23:53 25 4
gpt4 key购买 nike

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

关于python - 在 for 循环中 append 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59121303/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com