首页 > 解决方案 > 遍历矩阵并创建字典

问题描述

通过使用以下脚本,我可以获得每种矩阵类型的连接类型字典。我想在具有相似标题的新矩阵出现时更新值,如果标题不同,则在字典中添加不同的标题。当第二个矩阵出现时,我无法获得值的更新:

对于以下矩阵:

   0.0   2.0  1.0  1.0
   2.0   0.0  1.0  1.0
   1.0   1.0  0.0  1.0
   1.0   1.0  1.0  0.0

以列表 l 作为矩阵标题

l = ['A', 'A', 'B', 'B']

它成为了

      A    A     B     B
A   0.0   2.0  1.0  1.0
A   2.0   0.0  1.0  1.0
B   1.0   1.0  0.0  1.0
B   1.0   1.0  1.0  0.0

脚本

import collections
d = collections.defaultdict(dict)

for ix, iy in np.ndindex(matrix.shape):
        i = 1
        if int(matrix[ix][iy]) != 0:
            elem = l[ix]
            connection_index = matrix[ix][iy]
            connection_key = l[iy]
            if elm not in d[elm].keys(): 
                if connection_index ==1:
                    d[elm][connection_key +"_corner"] = i 
                elif connection_index ==2:
                     d[elm][connection_key +"_edge"] = i 
                elif connection_index >=3:
                     d[elm][connection_key +"_face"] = i
print(d)

给出:

defaultdict(dict,
            {'A': {'A_edge': 1, 'B_corner': 1},
             'B': {'A_corner': 1, 'B_corner': 1}})

现在当第二个矩阵出现时说和以前一样,那么它应该是

defaultdict(dict,
                {'A': {'A_edge': 2, 'B_corner': 2},
                 'B': {'A_corner': 2, 'B_corner': 2}})

但我仍然得到

defaultdict(dict,
                {'A': {'A_edge': 1, 'B_corner': 1},
                 'B': {'A_corner': 1, 'B_corner': 1}})

我知道的一件事是因为我需要更新'i',并在循环外尝试,但没有奏效。

这里,当矩阵元素为 2 时我们说边,当它是 1 时说角。例如 (A, A) 在第一行有 2 所以我们说

{'A': {'A_edge': 1}}

有人可以帮忙获得这个更新的结果吗?

提前致谢。

标签: python-3.x

解决方案


推荐阅读