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

我正在尝试将两个数组映射到一个字典列表。像这样:


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和,,以及移动部件断码成括号来回。


子衿沉夜
浏览 147回答 1
1回答

繁星淼淼

用 zipa_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'}]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python