如何循环遍历城市列表以计算它们之间的距离

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何循环遍历城市列表以计算它们之间的距离相关的知识,希望对你有一定的参考价值。

我正在研究脑筋急转弯,我想计算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]
答案

使用itertools.combinations()像:

Code:

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

Test Code:

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]))

Results:

[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

以上是关于如何循环遍历城市列表以计算它们之间的距离的主要内容,如果未能解决你的问题,请参考以下文章

读取城市坐标,计算任意两个城市之间的距离。

循环遍历表和字段列表并混合它们

如何计算两个 ZIP 之间的距离?

如何计算城市中两个区域之间的距离

如何使用谷歌地图api V3计算两个城市之间的距离[关闭]

按行驶距离过滤城市列表