以下代码中(假定每行一个路径,并且没有额外的空格)插入numpy的阵列的列表读取数据,然后演示如何计算两个点之间的距离。
import numpy as np
import numpy.linalg as la
#replace with your datafile
datafile = "../data/point_path.txt"
paths = []
with open(datafile, "r") as f:
for line in f:
point_strs = line.strip().strip("[()]").split("),(")
npoints = len(point_strs)
path = np.empty((npoints, 3))
for i in xrange(npoints):
path[i,:] = np.array(map(int, point_strs[i].split(",")))
paths.append(path)
print "First point of path 1:"
print paths[0][0]
print "Second point of path 2:"
print paths[1][1]
print "Euclidean Distance between these points:"
print la.norm(paths[0][0]-paths[1][1])
的这个输出是:
First point of path 1:
[ 0. 1. 3.]
Second point of path 2:
[ 0. 4. 5.]
Euclidean Distance between these points:
3.60555127546
编辑:如何格式化输入文件
代码假设点的每个列表是在其自己的行(例如,在F线,解析点的列表)。因此,以下文件:
[(0,2,3),(0,4,0)] [(1,4,5),(5,8,9),(3,4,0)] [(0,5,7),(0,6,8),(1,5,6),(5,8,10)]
将不起作用,因为所有3个列表位于同一行上。
这种格式:
[(0,2,3),(0,4,0)]
[(1,4,5),(5,8,9),(3,4,0)]
[(0,5,7),(0,6,8),(1,5,6),(5,8,10)]
将工作,为点的每个列表是一个单独的行。
您可以使用eval每行创建列表 –
你的意思是像导入加载数据从一个文件? – janbrohl
eval是非常神奇的...让我们看看我是否可以做到这一点 是的,它是一个文本文件。 –