【问题标题】:Given an array of points, how to get the distance between all the points in the array [duplicate]给定一个点数组,如何获得数组中所有点之间的距离[重复]
【发布时间】:2019-12-04 18:07:48
【问题描述】:

我有一个类似于 [1000, 562, 342, 123, 32, 0] 的数组,其中 0 始终是起点,这些值是从 0 开始的累积距离。

我想找到所有点之间的平均距离,但要获得平均距离,我需要将数组中的值减去它旁边的值。我的问题是我不确定如何获取减值,因为 0 不能减,因为它是数组中的最后一个值。

我尝试了for 循环:

for x in newdata:
    newdata[x] = newdata[x] - newdata[x-1]

但得到一个错误:

TypeError:列表索引必须是整数或切片,而不是浮点数

【问题讨论】:

  • 您必须遍历由列表长度定义的范围。
  • 这是数组还是列表?它看起来像一个列表。区分在python中非常重要。

标签: python arrays


【解决方案1】:

for 循环不会真正起作用,因为x in newdata 正在访问数组中的值。这是我的解决方案:

data =  [1000,562,342,123,32,0]
distances = [] 
avgDist = 0

# compute distances between points
for i in range(len(data) - 1):
  dist = data[i] - data[i+1]
  distances.append(dist) 

# get the average
avgDist = sum(distances)/len(distances)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-15
    • 2015-09-03
    • 1970-01-01
    • 2021-01-30
    • 2020-01-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多