0

如果我的问题太标准,我提前道歉。我尽力在谷歌上搜索答案,但找不到令人满意的答案。

我在 Jason 中有一个距离矩阵文件,格式如下

{“A”:{“A”:0,“B”:1,“C”:2},“B”:{“A”:1,“B”:0,“C”:1},“ C":{"A": 2, "B":1, "C":0}}

这告诉了任何两对之间的距离。比如 A 到 B 的距离是 1,在 Python 中如何将这个转换成矩阵形式?

谢谢!

4

1 回答 1

1

在编码之前,我们可以概述您的数据并定义您的问题:

你有顶点:

vertices = ["A", "B", "C"]

所以预期的矩阵是一个 3 x 3 二维数组(3 = 你的顶点数)

看起来像:

matrix = [
[0, 1, 2],  // edges's values staring from vertex A (edges: AA, AB, AC)
[1, 0, 1], // edges's values starting from vertex B (BA, BB, BC)
[2, 1, 0], // edges's values starting from vertex C (CA, CB, CC)
]

你现在的任务是通过代码而不是眼睛来构建上面的矩阵:D。所以解决方案是:

  • 定义你的顶点
  • 构建 (number_of_vertices x number_of_vertices) 矩阵
data = {'A': {'A': 0, 'B': 1, 'C': 2}, 'B': {'A': 1, 'B': 0, 'C': 1}, 'C': {'A': 2, 'B': 1, 'C': 0}} # Just a quick example, you can search how to read from file later

vertices = data.keys() # Your vertices is the dictionary's keys, use Python built-in method.
number_of_vertices = len(vertices)  # Count your vertices

matrix = []

for vertex1 in vertices:
  row = []  # Initialize a row represent values for edges starting from vertex1 to other vertices
  for vertex2 in vertices:
    row.append(data[vertex1][vertex2])  # Edge "vertex1" -> "vertex2"
  matrix.append(row)  # Add to our matrix

print(matrix)
# [[0, 1, 2], [1, 0, 1], [2, 1, 0]]

我使用了两个for ... in循环进行更清晰的演示。当你习惯了,你可以通过List Comprehension在 Python 中搜索和使用来缩短。

于 2022-02-26T04:37:00.537 回答