如何使用顺序键将Numpy数组转换为Python字典?

时间:2015-07-22 23:22:28

标签: python arrays numpy dictionary

我有一个像这样的numpy数组形式的矩阵:

myarray = np.array[[0,400,405,411,415,417,418,0]
                   [0,404,412,419,423,422,422,0]
                   [0,409,416,421,424,425,425,0]
                   [0,411,414,417,420,423,426,0]
                   [0,409,410,410,413,419,424,0]
                   [0,405,404,404,409,414,419,0]]

还有空字典:

dict = { }

在我的情况下,我想将该数组转换为python字典,其中字典的键是从左上值(myarray[0][0])计算的序号,直到右下角值(myarray[5][7])交错按行。 所以结果将是这样的:

dict = { 1 : 0, 2 : 400, 3: 405, ........, 47 : 419 ,48 : 0 } 

这种情况有什么解决方案吗? 希望得到你的帮助..非常感谢任何帮助..

1 个答案:

答案 0 :(得分:12)

使用flatten,然后在{1}}的帮助下从1开始创建词典:

enumerate

myarray = np.array([[0,400,405,411,415,417,418,0], [0,404,412,419,423,422,422,0], [0,409,416,421,424,425,425,0], [0,411,414,417,420,423,426,0], [0,409,410,410,413,419,424,0], [0,405,404,404,409,414,419,0]]) d = dict(enumerate(myarray.flatten(), 1)) 的输出:

d