我在计算像素之间的距离,我在计算x和y坐标的程序中做了一个鼠标回调函数。
这是我试过的密码,
def distance():
length = len(position)
# Distance in terms of x
distance_value = position[length-1][0] - position[length-2][0]
# Distance in terms of y
# distance_value = position[length-1][1] - position[length-2][1]
print("Value of pixel is: " + str(distance_value))IndexError:列出超出范围的索引。
发布于 2019-04-09 12:57:37
我想你需要做以下几件事:
def distance():
length = len(position)
# Distance in terms of x
try:
distance_value = position[length-1][0] - position[length-2][0]
print("Value of pixel is: " + str(distance_value))
except IndexError as e:
print('There is an error')
print(str(e))发布于 2019-04-09 13:04:14
我假设position是x,y对的列表。因此,在第一个位置,您的程序失败,因为没有位置可以比较。在这种情况下,您还可以使用if语句而不是try语句,这将捕获所有IndexError,即防止错误发生而不是捕获错误。
if len(position) > 1:
distance_value = position[-1][0] - position[-2][0]注意,您应该使用负索引来引用最后一个元素,而不是
length - x
https://stackoverflow.com/questions/55593355
复制相似问题