Kar*_*ara 13 python dictionary list
x = ['1', '2', '3', '4']
y = [[1,0],[2,0],[3,0],[4,]]
Run Code Online (Sandbox Code Playgroud)
我想创建一个字典,所以x和y值对应如下:
1: [1,0], 2: [2,0]
Run Code Online (Sandbox Code Playgroud)
等等
Igo*_*ato 24
你可以使用zip功能:
dict(zip(x, y))
>>> x = ['1', '2', '3', '4']
... y = [[1,0],[2,0],[3,0],[4,]]
>>> dict(zip(x, y))
0: {'1': [1, 0], '2': [2, 0], '3': [3, 0], '4': [4]}
Run Code Online (Sandbox Code Playgroud)
在python> 2.7中你可以使用dict理解:
>>> x = ['1', '2', '3', '4']
>>> y = [[1,0],[2,0],[3,0],[4,]]
>>> mydict = {key:value for key, value in zip(x,y)}
>>> mydict
{'1': [1, 0], '3': [3, 0], '2': [2, 0], '4': [4]}
>>>
Run Code Online (Sandbox Code Playgroud)
仍然是最好的答案
dict(zip(x,y))
在python <= 2.7中,您可以使用itertools.izip大型列表作为izip返回迭代器.对于像你这样的小清单,使用izip会过度.但请注意,itertools.izip在python 3 中消失了.在python 3中,zip内置函数已经返回迭代器,因此izip不再需要它.