python-3.x - 遍历矩阵并创建字典
问题描述
通过使用以下脚本,我可以获得每种矩阵类型的连接类型字典。我想在具有相似标题的新矩阵出现时更新值,如果标题不同,则在字典中添加不同的标题。当第二个矩阵出现时,我无法获得值的更新:
对于以下矩阵:
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 - django modelformset factory 'tuple' 对象没有属性 'author
- git - 从 Concourse 克隆 Bitbucket 上的 git 存储库的问题
- powerbi - 如何通过两个独立的切片器并排附加当前和以前的会话
- php - 如何在php中转换喜欢计数
- php - 为什么 sort_by_name 参数在 ActiveCollab API 上不起作用?
- autohotkey - AlwaysOnTop 不使用 AutoHotKey 中记录的语法
- ios - UIView.transition 延迟
- vuejs2 - 如何正确地将 getter 添加到 Vuex 模块?
- elasticsearch - 汇总结果显示的项目少于 doc_count?
- visual-studio - Visual Studio 2019 Preview 1 缺少 windows.h