【问题标题】:Appending list inside a for loop在 for 循环中附加列表
【发布时间】:2020-03-26 00:37:33
【问题描述】:

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

【问题讨论】:

  • 请添加输入和对应的预期输出
  • 好的,我添加了输入(文章)和停用词以及预期输出

标签: python list append nltk


【解决方案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】:

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

    【讨论】:

      【解决方案3】:

      您可以执行以下操作:

      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']]
      

      【讨论】:

      • @JohnSpencer 很高兴我能帮上忙!
      【解决方案4】:

      如果您更喜欢列表推导式,可以使用以下示例:

      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']]
      

      【讨论】:

      • 当你让它看起来如此简单,但我不敢相信我无法想到这一点。谢谢
      猜你喜欢
      • 2019-07-12
      • 2013-08-21
      • 1970-01-01
      • 1970-01-01
      • 2020-09-25
      • 2018-12-18
      • 1970-01-01
      • 2021-01-16
      • 1970-01-01
      相关资源
      最近更新 更多