gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 00:27:48 29 4
gpt4 key购买 nike

我有一个像这样的 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 } 

这种情况有什么解决办法吗?希望得到你的帮助.. 任何帮助将不胜感激..

最佳答案

使用flatten,然后借助enumerate从1开始创建字典:

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 的输出:

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

关于python - 如何使用顺序键将 Numpy 数组转换为 Python 字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31575675/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com