Python 距离公式计算器

0 投票
2 回答
1728 浏览
提问于 2025-04-17 02:53

我的作业是做一个距离计算器,用来计算两个地点之间的距离,我选择使用Python来实现。

我已经把所有地点都转化成了坐标点,但我需要知道怎么通过名字选择这两个地点,然后把距离公式应用到这两个地点上:

(sqrt ((x[2]-x[1])**2+(y[2]-[y1])**2) 

总之,我不需要你把整个程序写出来,只需要给我一些指引就行。

fort sullivan= (22.2, 27.2)
Fort william and mary= (20.2, 23.4)
Battle of Bunker II= (20.6, 22)
Battle of Brandywine= (17.3, 18.3)
Battle of Yorktown= (17.2, 15.4)
Jamestown Settlement= (17.2, 14.6)
Fort Hancock=(18.1, 11.9)
Siege of Charleston=(10.2, 8.9)
Battle of Rice Boats=(14.1, 7.5)
Castillo de San Marcos=(14.8, 4.8)
Fort Defiance=(13.9, 12.3)
Lexington=(10.5, 20.2)

2 个回答

3

用字典来存储元组:

location = {}
location['fort sullivan'] = (22.2, 27.2)
location['Fort william and mary'] = (20.2, 23.4)

或者你可以使用初始化语法:

location = {
  'fort sullivan': (22.2, 27.2),
  'Fort william and mary': (20.2, 23.4)
}

不过你可能想从文件中读取数据。

接着你可以写一个计算距离的函数:

def dist(p1, p2):
    return ((p1[0]-p2[0])**2 + (p1[1]-p2[1])**2)**0.5

然后你可以这样调用它:

print dist(
  location['fort sullivan'], 
  location['Fort william and mary']
)
4

你只需要把它们放进一个字典里,就像这样:

points = {
 'fort sullivan': (22.2, 27.2),
 'Fort william and mary': (20.2, 23.4)
}

然后从这个字典中选择你需要的内容,接着运行你的代码就可以了。

x = points['fort sullivan']
y = points['Fort william and mary']

# And then run math code

撰写回答