【发布时间】:2017-11-15 22:48:04
【问题描述】:
我在自己的名为 MTG.py 的文件中定义了以下函数。它应该以邻接矩阵作为输入,并创建一个图。
import pygraphviz as pgv
import numpy as np
def matrix_to_graph(M):
A = pgv.AGraph()
for i in range(0, np.shape(M)[0]):
for j in range(0, np.shape(M)[0]):
if i < j and M[i][j] == 1:
A.add_edge(i,j)
A.write('M.dot')
C = pgv.AGraph('M.dot')
C.layout()
C.draw('M.png')
当我从命令行运行时
from MTG import matrix_to_graph
M = [[0, 1, 0, 1, 1], [1, 0, 1, 1, 0], [0, 1, 0, 0, 0], [1, 1, 0, 0, 1], [1, 0, 0, 1, 0]]
matrix_to_graph(M)
我得到了我想要的,即打印到 M.png 的正确图表。
但是,如果我添加到上面的代码(没有缩进,即在函数定义之外)
M = input("Enter an adjacency matrix:")
matrix_to_graph(M)
我得到了错误
for i in range(0, np.shape(M)[0]):
IndexError: tuple index out of range
我想这是因为输入函数正在接受我认为是一个矩阵,但实际上是别的东西。我试图通过使用 np.matrix(M) 来纠正这个问题,但这会将我的矩阵变成 1x16 向量。我是 Python 新手,我确信有 1000 种方法可以更好地做到这一点,但我真的很想弄清楚为什么这种特殊方法不起作用。
我正在使用 PyCharm 2017.1.3(社区版,如果有的话)和 Python 3.6。
【问题讨论】:
标签: python python-3.x command-line pygraphviz