代码之家  ›  专栏  ›  技术社区  ›  BruceWayne

列表理解返回“生成器对象…”

  •  2
  • BruceWayne  · 技术社区  · 8 年前

    我正试图简洁地从字典中创建一个列表。

    以下代码有效:

    def main():
        newsapi = NewsApiClient(api_key=API_KEY)
        top_headlines = newsapi.get_everything(q="Merkel",language="en")
        news = json.dumps(top_headlines)
        news = json.loads(news)
        articles = []
        for i in news['articles']:
            articles.append(i['title'])
        print(articles)
    

    输出:

    ['Merkel “Helix Suppressor” Rifle and Merkel Suppressors', 'Angela Merkel', 
     'Merkel says Europe should do more to stop Syria war - Reuters', 
     'Merkel says Europe should do more to stop Syria war - Reuters', 
     'Merkel muss weg! Merkel has to go! Demonstrations in Hamburg', ... , 
     "Bruised 'Queen' Merkel Lives..."]
    

    但我在其他地方见过,并且一直在努力学习,列举理解。更换 for i in news['articles']: 循环方式:

    def main():
        ...
        articles = []
        articles.append(i['title'] for i in news['articles'])
        print(articles)
    

    我本来希望得到类似的结果。相反,它返回:

    [<generator object main.<locals>.<genexpr> at 0x035F9570>]
    

    我找到了 this related solution 但是执行以下操作会输出标题(yay!)三次(boo!):

    def main():
        ...
        articles = []
        articles.append([i['title'] for x in news for i in news['articles']])
        print(articles)
    

    通过列表理解生成文章的正确方法是什么?

    忽略我的例行程序 main() 而不是调用函数。稍后我会解决的。

    2 回复  |  直到 8 年前
        1
  •  2
  •   OriolAbril    8 年前

    仅使用:

    articles = [i['title'] for i in news['article']]
    

    列表理解已经返回了一个列表,因此不需要创建一个空的列表,然后向其追加值。对于清单上的Gide理解,您可以查看 this one .

    关于生成器对象,这里的问题是使用 () (或者只是在它们没有被封闭时)将创建一个生成器而不是一个列表。有关生成器的更多信息以及它们与列表的区别,请参见 Generator Expressions vs. List Comprehension 关于发电机的理解,请参见 How exactly does a generator comprehension work? .

        2
  •  0
  •   Matt_G    8 年前

    在上下文中使用它,生成一个生成器:

     articles.append(i['title'] for x in news for i in news['articles'])
    

    这样使用会生成一个列表:

    articles = [i['title'] for i in news['articles']]