【问题标题】:How to iterate through a list of coordinates and calculate distance between them?如何遍历坐标列表并计算它们之间的距离?
【发布时间】:2020-05-10 03:58:48
【问题描述】:

在一个列表中,有带有 x 和 y 值的坐标。

[(7, 9), (3, 3), (6, 0), (7, 9)]

我可以计算两点之间的距离。

distance_formula = math.sqrt(((x[j]-x[i])**2)+((y[j]-y[i])**2))

我很难浏览列表并计算每个点之间的距离。我要计算第一个索引和第二个索引、第二个索引和第三个索引、第三个索引和第四个索引之间的距离...

【问题讨论】:

  • 您在迭代列表的哪个部分遇到了困难?是否有某个特定部分您无法理解?也许您可以展示您尝试过的方法以及为什么它不起作用

标签: python list iterator coordinates distance


【解决方案1】:

您可以使用zip() 做到这一点。 zip() 会制作成对的坐标,让你方便地遍历它们。

coordinates = [(7, 9), (3, 3), (6, 0), (7, 9)]

for (x1, y1), (x2, y2) in zip(coordinates, coordinates[1:]):
    distance_formula = math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
    print(distance_formula)

【讨论】:

    【解决方案2】:

    带有List Comprehensions

    import math
    
    xy = [(7, 9), (3, 3), (6, 0), (7, 9)]
    
    distances = [math.sqrt(((xy[i+1][0]-xy[i][0])**2)+((xy[i+1][1]-xy[i][1])**2)) for i in range(len(xy)-1)]
    
    print(distances)
    
    >>> [7.211102550927978, 4.242640687119285, 9.055385138137417]
    

    【讨论】:

      【解决方案3】:

      据我了解,您想找到点 0 和点 1、点 1 和点 2 之间的距离...

      如果是这样,这就是你的答案

      i = 0
      n = [(7, 9), (3, 3), (6, 0), (7, 9)]
      result = []
      
      for item in range(len(n)-1):
         distX = abs(n[i][0] - n[i+1][0])
         distY = abs(n[i][1] - n[i+1][1])
      
         hypotenuse = math.sqrt((distX*distX) + (distY*distY)) 
         result.append(hypotenuse)
      
         i =i + 1
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-03-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-05-05
        相关资源
        最近更新 更多