【问题标题】:how to calculate distance between two points within the same list如何计算同一列表中两点之间的距离
【发布时间】:2022-11-03 15:04:19
【问题描述】:

我有一个名为“cords”的列表,其中包含列表中的所有 x-y 坐标。 我需要计算 1st(x,y) 和 2nd(x,y) 之间的距离,然后是 2nd(x,y) 和 3rd(x,y) 坐标,依此类推,直到列表结束。列表中的值是浮点数。

我在用

定义查找距离():

    for i in range (0, (len(cords))):
        res = [float(ele) for ele in cords[i]]
        dis. append(res)
        for j in range (1, ((len(cords))-1)):
            dist=math.sqrt((cm.dis[i][0] - cm.dis[j][0])**2 + (cm.dis[i][1] - cm.dis[j][1])**2)
            dista. append(dist)
 return res , dista

            

这会引发列表索引超出范围的错误,我该如何解决?

【问题讨论】:

  • 首先,请阅读您应用的标签的描述。他们实际上是矛盾的。此外,删除图像并复制'n'粘贴其中包含的文本。此外,请考虑提供从您的代码中提取的minimal reproducible example。作为这里的新用户,也请使用tour 并阅读How to Ask

标签: python python-3.x python-2.7


【解决方案1】:

您应该使用zip,因为zip 将迭代直到用尽任何提供的列表

from math import sqrt
points = [(1,2.3), (3.4, 5.6), (2.3, 7.8)]
res = [ sqrt((y[0]-x[0])**2 + (y[1]-x[1])**2) for x,y in zip(points, points[1:]) ]

【讨论】:

    猜你喜欢
    • 2010-10-30
    • 1970-01-01
    • 2011-12-21
    • 2019-01-10
    • 1970-01-01
    • 2020-05-09
    • 2011-04-23
    相关资源
    最近更新 更多