[英]One-to-one correspondence list of dictionaries based on two nested list
I have two nested lists:我有两个嵌套列表:
a = [[0, 1],[1, 0],[2, 0]]
b = [[2, 1],[1, 3],[8, 1]]
I want to have a list of dictionaries such that each inner element of list a
(as key) corresponds to it's inner element of list b
(as value).我想要一个字典列表,使得列表
a
每个内部元素(作为键)对应于它的列表b
的内部元素(作为值)。
Here's my desired output: [{0:2,1:1},{1:1,0:3},{2:8,0:1}]
这是我想要的 output:
[{0:2,1:1},{1:1,0:3},{2:8,0:1}]
I've tried:我试过了:
ls = []
for i in a:
for j in b:
ls.append({k:v for k,v in zip(i, j)})
print(ls)
But it gives me all the possible combinations which I don't want.但它给了我所有我不想要的可能组合。 Any help is appreciated.
任何帮助表示赞赏。
You use a list comprehension and zip
.您使用列表理解和
zip
。
>>> a = [[0, 1],[1, 0],[2, 0]]
>>> b = [[2, 1],[1, 3],[8, 1]]
>>> [dict(zip(i, j)) for i, j in zip(a, b)]
[{0: 2, 1: 1}, {1: 1, 0: 3}, {2: 8, 0: 1}]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.