list comprehension returning “generator object…”

人走茶凉 提交于 2020-01-24 09:49:16

问题


I'm trying to succinctly create a list from a dictionary.

The following code works:

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)

output:

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

But I've seen elsewhere, and been trying to learn, list comprehension. Replacing the for i in news['articles']: loop with:

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

I was expecting to get a similar output. Instead it returns:

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

I found this related solution but doing the following outputs the titles (yay!) three times (boo!):

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

What is the correct way to generate the articles via list comprehension?

Ignore that I have routines in main() instead of calls to functions. I will fix that later.


回答1:


Just use:

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

The list comprehension already return a list, so there is no need to create an empty one and then append values to it. For a gide on list comprehensions you may check this one.

Regarding the generator object, the issue here is that using list comprehensions between () (or simply when they are not enclosed) will create a generator instead of a list. For more info on generators and how are they different than lists, see Generator Expressions vs. List Comprehension and for generator comprehentions, see How exactly does a generator comprehension work?.




回答2:


Using it in the context you are, produces a generator:

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

Using it like this produces a list:

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


来源:https://stackoverflow.com/questions/50494638/list-comprehension-returning-generator-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!