pep*_*epe 3 python arrays dictionary
假设此列表:
a = [0.41 1.87 1.10 7.05]
Run Code Online (Sandbox Code Playgroud)
我想建立一个看起来如下的字典:
d = {0: 0.41, 1: 1.87, 2: 1.10, 3: 7.05}
Run Code Online (Sandbox Code Playgroud)
关于如何从列表转换为dict的SO有很多答案,但是我找不到解决这个特定需求的答案(即dict的键值是列表的元素索引).
我可以成像这里有繁琐的方法,例如使用for循环,获取a.index(i),追加,压缩等但我想知道我是否缺少更有效的方法来构建这个字典.
您可以使用dict理解来实现此目的!
>>> d= [0.41,1.87,1.10,7.05]
>>> {index:i for index,i in enumerate(d)}
{0: 0.41, 1: 1.87, 2: 1.1, 3: 7.05}
Run Code Online (Sandbox Code Playgroud)