Python距离公式计算器

时间:2011-09-22 22:39:36

标签: python

我的任务是制作一个距离计算器,找出两个位置之间的距离,然后我选择使用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 个答案:

答案 0 :(得分: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

答案 1 :(得分:3)

使用dict存储元组:

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

或者您可以使用intializer语法:

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']
)
相关问题