list comprehension返回“generator object ...”

时间:2018-05-23 17:55:57

标签: python list-comprehension

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

以下代码有效:

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..."]

但我在其他地方看到过,并且一直在努力学习,列出理解力。用{:1>替换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但是做了以下输出标题(耶!)三次(嘘!):

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

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

忽略我在main()中有例程,而不是调用函数。我稍后会解决这个问题。

2 个答案:

答案 0 :(得分:1)

替换:

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

与:

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

答案 1 :(得分:0)

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

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

像这样使用会产生一个列表:

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