python 2d数组到dict [英] python 2d array to dict
本文介绍了python 2d数组到dict的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想创建一个表示为2d数组的对称矩阵的下三角形的dict。例如,如果numpy数组是;
I want to create a dict from lower triangle of a symmetric matrix represented as 2d array. For examples if the numpy array is;
array([[0, 2, 3],
[2, 0, 4],
[3, 4, 0]])
然后我想字体看起来像;
then I want the dict to look like;
{('1', '0'): 2, ('2', '0'): 3, ('2', '1'): 4}
post for vector;
There is a similar post for vector;
Fastest way to convert a Numpy array into a sparse dictionary?
我比较新的python所以任何帮助/ suggestoins赞赏。
I am relatively new to python so any help/suggestoins appreciated.
推荐答案
>>> arr =[[0, 2, 3],
[2, 0, 4],
[3, 4, 0]]
>>> dict(((j,i), arr[i][j]) for i in range(len(arr)) for j in range(len(arr[0])) if i<j)
{(2, 0): 3, (1, 0): 2, (2, 1): 4}
这篇关于python 2d数组到dict的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文