【发布时间】:2020-04-17 19:16:13
【问题描述】:
我创建了一个简单的测距函数,它需要 2 个整数和 2 个数组。它计算如图所示的距离,并将距离作为数组返回。我不知道为什么,但我遇到了错误。任何想法为什么和任何建议来解决?
xs = [1,2,3,4,5,6]
ys = [7,8,9,10,11,12]
def distance(t0, t1, x, y):
distance = []
for i in range(len(x)):
distance[i] = (abs(t1 * x[i] + t0 + y[i])) / (((t1**2)+(1))**0.5) #the distance formula of a point to a line. point = (x,y) , line = t0+t1*x
return distance
print(distance(3,6,xs,ys))
Traceback (most recent call last):
File "ml2.py", line 10, in <module>
print(distance(3,6,xs,ys))
File "ml2.py", line 7, in distance
distance[i] = (abs(t1 * x[i] + t0 + y[i])) / (((t1**2)+(1))**0.5)
IndexError: list assignment index out of range
【问题讨论】:
-
距离需要使用 append 方法,因为它是一个列表,并且该列表中没有任何元素。
-
distance.append((abs(t1 * x[i] + t0 + y[i])) / (((t1**2)+(1))**0.5)跨度>