python 2d数组到字典 [英] python 2d array to dict

查看:36
本文介绍了python 2d数组到字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从表示为二维数组的对称矩阵的下三角形创建一个字典.例如,如果 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}

vector 也有类似的帖子;

There is a similar post for vector;

转换 Numpy 数组的最快方法成稀疏字典?

我对 python 比较陌生,所以感谢任何帮助/建议.

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数组到字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆