为了账号安全,请及时绑定邮箱和手机立即绑定

单行 for 循环以构建具有多个值的字典列表

单行 for 循环以构建具有多个值的字典列表

子衿沉夜 2021-11-02 19:32:54
我正在尝试将两个数组映射到一个字典列表。像这样:a_list = [1, 2, 3]b_list = ["a", "b", "c"]d = [{"key1": a, "key2": b} for a in a_list for b in b_list]>> [{"key1": 1, "key2": "a"}, {"key1": 2, "key2": "b"}, {"key1": 3, "key2": "c"}]但是,这给出了:[{"key1": 1, "key2": "a"}, {"key1": 1, "key2": "b"}, [...] {"key1": 3, "key2": "b"}, {"key1": 3, "key2": "c"}]我试着更换第二for既and和,,以及移动部件断码成括号来回。
查看完整描述

1 回答

?
繁星淼淼

TA贡献1775条经验 获得超11个赞

用 zip


a_list = [1, 2, 3]

b_list = ["a", "b", "c"]

d = [{"key1": a, "key2": b} for (a, b) in zip(a_list, b_list)]

print(d)  # [{'key1': 1, 'key2': 'a'}, {'key1': 2, 'key2': 'b'}, {'key1': 3, 'key2': 'c'}]



查看完整回答
反对 回复 2021-11-02
  • 1 回答
  • 0 关注
  • 146 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信