我正在尝试将两个数组映射到一个字典列表。像这样: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'}]
添加回答
举报
0/150
提交
取消