【问题标题】:Functions works on command line, but not in script函数适用于命令行,但不适用于脚本
【发布时间】: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


    【解决方案1】:

    Python 3 的 input 返回一个 str,它不会仅仅因为内容看起来像 Python 文字就解析它以创建 Python 数据结构。在这种情况下,如果您希望能够输入listints 文字的list,我建议using ast.literal_eval (安全地)从表示矩阵文字的字符串转换为@987654328 @本身:

    import ast
    
    M = ast.literal_eval(input("Enter an adjacency matrix:"))
    

    您可能已经习惯了 Python 2,其中 input 相当于在 Python 3 中执行 eval(input(...)),但是那个版本的 input 很危险,并且有充分的理由被删除; ast.literal_eval 让你得到你需要的东西,而不允许任意代码执行。

    【讨论】:

    • 我很高兴我知道问题出在哪里,更高兴的是修复非常简单。谢谢。
    猜你喜欢
    • 2015-02-24
    • 1970-01-01
    • 1970-01-01
    • 2011-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-17
    • 1970-01-01
    相关资源
    最近更新 更多