如何为这个Python 3.x列表循环编写一行生成器?

huangapple go评论63阅读模式
英文:

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}

huangapple
  • 本文由 发表于 2023年5月26日 13:26:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/76337877.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定