我试图找出如何计算使用在一个文本文件中的坐标的线段的长度计算点之间的距离:试图从一个.txt文件
X,Y format (x,y,x,y,x,y,etc...)
4.5,10.0,4.5,5.7,5.5,2.5,6.5,0.3,6.8,0.0,1.0,1.0,3.5,3.5,2,5,6.0,2.0
这是我到目前为止:
Python
# -*- coding: cp1252 -*-
#Starter code for GIS301 Lab 2
#GIS301Lab2Starter.py
import math
#-----------------------------------------------------------
#Procedure for reading a coordinate text file
#in x1,y1,x2,y2,… xn,yn format
#and resulting in a list as type float
#open file to read
file = open(r'C:\Users\Tristan\Desktop\USB_Backup_10-4-16\2016-2017\Fall2016\SpatialDataStructures\Labs\Lab2\points.txt','r')
#read file to string
coordString = file.read()
#Split coordString into list elements
coordList = coordString.split(',')
#convert from string to float type
for index, item in enumerate(coordList):
coordList[index] = float(coordList[index])
file.close
#-----------------------------------------------------------
print (coordList)
#add more code here
numPoints = len(coordList)/2
print("Number of Points")
print (numPoints)
x = [float(r) for r in coordList[0::2]]
y = [float(r) for r in coordList[1::2]]
xy = list(zip(x,y))
# pre-define distance and add subsequent distances
dist = 0
for r in coordList(len(xy)-1):
dist += ((xy[r][0]-xy[r+1][0])**2 + (xy[r][1]-xy[r+1][1])**2)**0.5
print (dist)
#for r in coordList(len(xy)-1):
# dist += ((xy[r][0]-xy[r+1][0])**2 + (xy[r][1]-xy[r+1][1])**2)**0.5
When I run it in PyhthonWin:
Traceback (most recent call last):
File "C:\Users\Tristan\Desktop\USB_Backup_10-4-16\2016-2017\Fall2016\SpatialDataStructures\Labs\Lab2\GOERSLab2.py", line 39, in <module>
for r in coordList(len(xy)-1):
TypeError: 'list' object is not callable
的方程n用于计算两点之间的距离为: http://i.stack.imgur.com/vOcu0.png
然后我需要将它们全部加起来!
错误来自哪里,哪一行? – MooingRawr
我不明白'coordString.replace(',','')]'coordList'coordList = [float(coordList)'的用途。事实上,简单地删除该行似乎给你一个完全按照你想要的格式的列表。这是书面的奇怪操作;你会想'coordList = [float(item)for coordList]''。但正如我所说,这是多余的 – roganjosh
你正在做的事实际上归结为'['string_with_no_separators中a_list的float(a_list)] .... ....这并没有太大的意义。 – roganjosh