简体   繁体   English

python3.7 IndexError:列表索引超出范围问题

[英]python3.7 IndexError: list index out of range problem

I have faced an error IndexError: list index out of range when I ran my_function(1, data) . 我运行my_function(1, data)时遇到错误IndexError: list index out of range This function should find distance between given point id and other points. 此函数应查找给定点id与其他点之间的距离。

Code: 码:

import math 

p = []
point_dist = []
distance = 0
data = [[1, 5, 2], [2, 6, 2], [3, 7, 2], [4, 8, 2]]

def my_function(point_id,data):
    print(len(data))   
    p.append(data[point_id])
    data.pop(point_id)
    print(len(data))

    for i in range(0, 3, 1):
        for j in range(0, 3, 1):
            distance = math.sqrt(pow(p[0][j] - data[i][j], 2))

Error : 错误

File "C:\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 110, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

File "C:/Users/ay/YandexDisk/python/1/untitled1.py", line 13, in <module>
    distance=math.sqrt(pow(p[0][j]-data[i][j],2))

IndexError: list index out of range

You never called your function my_function which populate you array p . 您从未调用函数my_function来填充数组p So your array is empty, and you can't access the [0][j] element. 因此,您的数组为空,并且您无法访问[0][j]元素。

You only defined a function with the name my_function() Then you have to call it first to get p list . 您只定义了一个名称为my_function()的函数,然后必须首先调用它以获得p list Furthermore I prefer explicitely returning p and data : 此外,我更喜欢显式返回pdata

import math 

p=[]
point_dist=[]
distance=0
data=[[1,5,2],[2,6,2],[3,7,2],[4,8,2]]

def my_function(point_id, data):
    print(len(data))   
    p.append(data[point_id])
    data.pop(point_id)
    print(len(data))

    return p, data

p, data = my_function(1, data)

for i in range(0,3,1):
    for j in range(0,3,1):
     distance=math.sqrt(pow(p[0][j]-data[i][j],2))

Out: 出:

4
3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM