英文:
How do I write a one-line generator for this Python 3.x list cycle?
问题
如何正确制作这个循环的生成器?
我是一名初学者程序员,不要过于苛刻地评判我,导师要求我在一行代码中写出这个循环。
post_id_detail = {post['id']: post for post in posts}
帮助您制作正确的一行生成器。
英文:
How to make a generator of this cycle correctly?
I am a novice programmer, do not judge strictly, the Mentor asks me to write this cycle in one line
for post in posts:
post_id_detail[post['id']] = post
I do this but it doesn't work
post = [post_id_detail[post['id']] for post in posts]
Help to make the right generator in one line
答案1
得分: 1
post_id_detail
显然是一个字典,而不是一个列表,所以请使用字典推导式代替:
post_id_detail = {post['id']: post for post in posts}
英文:
post_id_detail
is apparently a dict rather than a list, so use a dict comprehension instead:
post_id_detail = {post['id']: post for post in posts}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论