使用将字母值转换为 python 中的数字的字典创建邻接矩阵

Create an adjacency matrix using a dictionary with letter values converted to numbers in python

所以我有一个包含字母值和键的字典,我想使用数字(0 或 1)生成一个邻接矩阵。但我不知道该怎么做。

这是我的词典:

g = { "a" : ["c","e","b"],
      "b" : ["f","a"]}

我想要这样的输出:

import numpy as np

new_dic = {'a':[0,1,1,0,1,0],'b':(1,0,0,0,0,1)}
rows_names = ['a','b'] # I use a list because dictionaries don't memorize the positions

adj_matrix = np.array([new_dic[i] for i in rows_names])

print(adj_matrix)

输出:

[[0 1 1 0 1 0]
[1 0 0 0 0 1]]

所以它是一个邻接矩阵:column/row 1代表A,column/row 2代表B ...

谢谢!

我不知道它是否有帮助,但这是我使用 ascii 将所有字母转换为数字的方法:

for key, value in g.items():
    nums = [str(ord(x) - 96) for x in value if x.lower() >= 'a' and x.lower() <= 'z']
    g[key] = nums
print(g)

输出:

{'a': ['3', '5', '2'], 'b': ['6', '1']}

所以 a == 1 b == 2 ...

所以我的问题是:如果 a 使用第一个值 "e" 的键 a,我应该怎么做才能在第 5 列第 1 行而不是第 2 列第 1 行中找到 e ?并将 e 替换为 1

使用理解:

g = {'a': ['c', 'e', 'b'], 'b': ['f', 'a']}
vals = 'a b c d e f'.split()  # Column values

new_dic = {k: [1 if x in v else 0 for x in vals] for k, v in g.items()}