1

我有一个从文件中读取信息的代码(行描述点、多边形、线和圆)并将其解析为相应的类。Point 有 x 和 7 坐标,Line 有起点和终点。

我有一个列表 ( line = ['L1','L((1,1), (1,2))','# comment']),我试着把它排成一行。问题在于创建端点,执行时出现以下ValueError: invalid literal for int() with base 10: ''错误x2

问题是什么?

代码:

def make_line(line):
        name = line[0]
        point = line[1].split(", ")
        p = point[0].split(",")
        x1 = int(p[0][3:])
        y1 = int(p[1][:-1])
        point1 = Point(x1,y1)
        p = point[1].split(",")
        x2 = int(p[0][1:])
        y2 = int(p[1][:-2])
        point2 = Point(x2,y2)
        line = Line(point1,point2)
        shapes[name] = line
4

3 回答 3

6

You error message says you are trying to convert an empty string to an int. Double check all your data immediately before doing the conversion to verify this.

It is an absolute certainty that if the data is correct, the cast to integer will work. Therefore, the only conclusion to be drawn is that your data is incorrect. You are claiming in comments to your question that the data is good, but that simply cannot be true.

Trust the python interpreter over your own assumptions.

于 2013-05-19T16:55:29.680 回答
0

该错误表明您的代码有问题,但实际上它运行正确。如果您遇到错误,值得找到它们发生的行,并使用print打印它们的值以绝对确保您将正确的值传递给正确的方法。

处理这种(乍一看)有趣格式的简单方法是使用 python 的eval()函数。你会注意到列表的第二部分看起来很像一组两个集合,事实上它是。

如果你这样做,你会得到一个很好的集合对象:

eval("((1,1), (1,2))")
# equivalent to this:
eval(line[1][1:],{}) # passing an empty dict as the 2nd argument makes eval a (bit) safer

但这只是一种快速而肮脏的方法,永远不应该在生产代码中使用。

于 2013-05-19T16:59:40.060 回答
0

我删除了您没有提供足够信息的部分,但我仍然没有收到相同的错误。

def make_line(line):
    name = line[0]
    point = line[1].split(", ")
    p = point[0].split(",")
    x1 = int(p[0][3:])
    y1 = int(p[1][:-1])
    p = point[1].split(",")
    x2 = int(p[0][1:])
    y2 = int(p[1][:-2])
    return x1, y1, x2, y2

>>> make_line(['L1','L((1,2), (1,1))','# comment'])
(1, 2, 1, 1)
于 2013-05-19T16:59:42.503 回答