【问题标题】:Taking Array and integer as arguments and returning an array以数组和整数作为参数并返回一个数组
【发布时间】: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)跨度>

标签: python arrays function


【解决方案1】:

您的列表distance 的长度为0(您可以使用print len(distance) 进行验证)。这意味着它没有索引。您正在尝试将某些内容分配给不存在的索引0。您可能想要做的是append 到列表中:

distance.append((abs(t1 * x[i] + t0 + y[i])) / (((t1**2)+(1))**0.5))

【讨论】:

    猜你喜欢
    • 2011-05-27
    • 2021-11-20
    • 2022-08-05
    • 2021-06-15
    • 2019-10-18
    • 2021-10-17
    • 2014-06-27
    • 1970-01-01
    • 2020-07-08
    相关资源
    最近更新 更多