简体   繁体   English

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

[英]How to convert Numpy Array to Python Dictionary with Sequential Keys?

I have a matrix in the form of a numpy array like this : 我有一个像这样的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]]

and also empty dictionary : 还有空字典:

dict = { }

In my case, i want to convert that array to python dictionary where the keys of dictionary are sequential number calculated from up-left value ( myarray[0][0] ) until bottom-right value ( myarray[5][7] ) interleaved by row. 在我的情况下,我想将该数组转换为python字典,其中字典的键是从左上值( myarray[0][0] )计算的序号,直到右下角值( myarray[5][7] )按行交错。 So the result will be like this : 所以结果将是这样的:

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

is there any solution for this condition? 有这种情况的解决方案吗? wish for your help.. Any help would be very appreciated.. 希望得到你的帮助..任何帮助将非常感谢..

Use flatten and then create the dictionary with the help of enumerate starting from 1: 使用flatten ,然后使用从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))

Output of d : 输出d

{1: 0,
 2: 400,
 3: 405,
 4: 411,
 5: 415,
 6: 417,
 7: 418,
 8: 0,
 9: 0,
 10: 404,
 ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM