返回“生成器对象..."的列表理解 [英] list comprehension returning "generator object..."

查看:72
本文介绍了返回“生成器对象..."的列表理解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从字典中简洁地创建一个列表.

以下代码有效:

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

我发现了此相关解决方案,但是执行以下操作后,标题输出了(是!)三次(嘘!):

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

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

忽略我在main()中有例程而不是对函数的调用.我待会儿解决.

解决方案

只需使用:

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

列表理解已经返回了一个列表,因此无需创建一个空列表,然后将值附加到该列表中.要获得有关列表理解的帮助,您可以检查这一个.

关于生成器对象,这里的问题是,在()之间使用列表推导(或者简单地在不包含它们时)将创建一个生成器,而不是一个列表.有关生成器及其与列表的区别的更多信息,请参见生成器表达式与列表理解以及有关生成器理解的信息,请参见生成器理解的工作原理是什么?.

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.

解决方案

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?.

这篇关于返回“生成器对象..."的列表理解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆