有一个电子邮件ID列表,需要将密钥“电子邮件”添加到列表中的每个元素。电子邮件清单:
user = ["[email protected]","[email protected]"]
这里要添加电子邮件密钥,输出应为as。[{'email':'[email protected]'},{'email':'[email protected]'}]
为了这,
email_object = {}
email_list = []
user = ["[email protected]","[email protected]"]
for i in user:
email_object["email"] = i
email_list.append(email_object)
print(email_list)
结果:
[{'email': '[email protected]'}, {'email': '[email protected]'}]
结果中仅显示列表中的最后一个电子邮件地址。如何将输出结果显示为:
[{'email': '[email protected]'}, {'email': '[email protected]'}]
您可以像下面这样使用list-comprehension:
users = ["[email protected]","[email protected]"]
res = [{"email": v} for v in users]
这将导致:
[{'email': '[email protected]'}, {'email': '[email protected]'}]
使用代码时遇到的问题是,您email_object
在更改列表时将的相同副本附加到列表中。
您可以按以下方式修改代码以使其按预期工作:
...
email_list.append(email_object.copy())
...
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句