将以下数据保存在名为axis.txt的文件中。
A,0,0;B,3,4
C,4,7;D,2,9
E,8,2;F,0,6
文件的每一行都包含一个点的名称及其X-Y坐标,一个分号,然后是第二个点的名称及其X-Y坐标,格式为:
<Name1>:X1,Y1;<Name2>:X2,Y2
;
编写脚本以使用以下公式计算距离和城市街区距离:
distance = math.sqrt((x1 - x2)**2 + (y1 - y2)**2)
City Block Distance = |(X1-X2)|+|(Y1-Y2)|
因此,脚本的输出变为:
我曾尝试从excel导入数据,但是我是新手,所以对如何实现此目的没有太多的了解。
答案 0 :(得分:0)
假设coordinates.txt
与Python脚本位于同一目录中:
with open("coordinates.txt", 'r') as coordinates_file:
for line in coordinates_file:
# delete trailing new-line character
line = line.rstrip()
# unpack points (e.g. "A,0,0")
point_1, point_2 = line.split(";")
# name_* is for example "A"; loc*_tmp is a string representation of coords
name_1, *loc1_tmp = point_1.split(",")
# change coords to int
loc1 = [int(loc) for loc in loc1_tmp]
name_2, *loc2_tmp = point_2.split(",")
loc2 = [int(loc) for loc in loc2_tmp]
euclidian_distance = math.sqrt((loc1[0] - loc2[0])**2 + (loc1[1] - loc2[1])**2)
block_distance = abs(loc1[0] - loc2[0]) + abs(loc1[1] - loc2[1])
print("The distances between {} and {}:".format(name_1, name_2))
print("Euclidian distance {}".format(euclidian_distance))
print("Block distance {}".format(block_distance))