我正在尝试从字典中简洁地创建一个列表。
以下代码有效:
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 但执行以下操作输出标题(耶!)三遍(嘘!):
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']]
列表推导式已经返回一个列表,因此无需创建一个空列表然后向其附加值。有关列表理解的指南,您可以查看 this one 。
关于生成器对象,这里的问题是在
()
之间使用列表推导式(或者只是当它们没有被包围时)将创建一个生成器而不是列表。有关生成器的更多信息以及它们与列表的不同之处,请参阅 Generator Expressions vs. List Comprehension,有关生成器的理解,请参阅 How exactly does a generator comprehension work? 。关于python - 列表理解返回 "generator object...",我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50494638/