【问题标题】:How to loop through list of cities to calculate distances between them如何遍历城市列表以计算它们之间的距离
【发布时间】:2019-02-20 04:06:50
【问题描述】:

我正在做一个脑筋急转弯,我想计算 4 个城市之间所有可能的距离。我写了一个函数,你可以输入两个城市的 x 和 y 坐标,它会计算它们之间的距离。

虽然我可以单独调用该函数 6 次, 如果数据集变得更大,这似乎效率低下。我想我应该使用嵌套的“for循环”,但我想不出一种方法来正确地增加内部循环。

我最初的想法是创建一个对象列表并在内部循环中使用它。

import math #Imports the math module

def calc_euclidean(x1,y1,x2,y2): #Function takes 4 arguments
    xDistancesqrd=math.pow((x2-x1),2) #x2-x1 squared
    yDistancesqrd=math.pow((y2-y1),2) #y2-y1 squared
    euclideanDistance=math.sqrt(xDistancesqrd+yDistancesqrd) #distance=square root (x2-x1)^2+(y2-y1)^2
    return euclideanDistance #Returns the result of the calculation, the euclidean distance between the points.

Budapest=[47.4979, 19.0402]
Vienna=[48.210033, 16.363449]
Sofia=[42.6977, 23.3219]
Zagreb=[45.8150, 15.9819]

cities=[Budapest,Vienna,Sofia,Zagreb]

【问题讨论】:

  • 您可以通过应用毕达哥拉斯定理来计算球体角度(度)。
  • @KlausD。这就是 OP 似乎正在做的事情。
  • @Selcuk 我的自动更正对我的打击比平时更大:你不能这样做...
  • @KlausD。具有讽刺意味的是,毕达哥拉斯也是第一个提出球形地球的人。话虽如此,毕达哥拉斯定理是欧洲城市的一个很好的近似值,因为与地球的大小相比,它们彼此非常接近,因此可以假设它们在一个平面上。
  • 请不要在回答后对问题进行大量编辑。如果您有新问题,请提出新问题。

标签: python loops nested-loops


【解决方案1】:

使用itertools.combinations() 喜欢:

代码:

for c1, c2 in it.combinations(cities, 2):
    print(c1, c2, calc_euclidean(c1[0], c1[1], c2[0], c2[1]))

测试代码:

import math  # Imports the math module
import itertools as it


def calc_euclidean(x1, y1, x2, y2):  # Function takes 4 arguments
    xDistancesqrd = math.pow((x2 - x1), 2)  # x2-x1 squared
    yDistancesqrd = math.pow((y2 - y1), 2)  # y2-y1 squared
    euclideanDistance = math.sqrt(
        xDistancesqrd + yDistancesqrd)  # distance=square root (x2-x1)^2+(y2-y1)^2
    return euclideanDistance  # Returns the result of the calculation, the euclidean distance between the points.


Budapest = [47.4979, 19.0402]
Vienna = [48.210033, 16.363449]
Sofia = [42.6977, 23.3219]
Zagreb = [45.8150, 15.9819]

cities = [Budapest, Vienna, Sofia, Zagreb]
for c1, c2 in it.combinations(cities, 2):
    print(c1, c2, calc_euclidean(c1[0], c1[1], c2[0], c2[1]))

结果:

[47.4979, 19.0402] [48.210033, 16.363449] 2.769860885620431
[47.4979, 19.0402] [42.6977, 23.3219] 6.432330443159777
[47.4979, 19.0402] [45.815, 15.9819] 3.4907522541710128
[48.210033, 16.363449] [42.6977, 23.3219] 8.877266213327731
[48.210033, 16.363449] [45.815, 15.9819] 2.4252345681376934
[42.6977, 23.3219] [45.815, 15.9819] 7.974531916670721

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-06
    • 1970-01-01
    • 2016-06-07
    • 1970-01-01
    • 1970-01-01
    • 2011-03-25
    • 1970-01-01
    相关资源
    最近更新 更多