简体   繁体   English

Python for loop: IndexError: list index out of range

[英]Python for loop: IndexError: list index out of range

I am new with Python, This is my code:我是 Python 的新手,这是我的代码:

import numpy as np

x = [0, 0, 0, 0, 5, 0, 10, 5]
y = [4, 4, 4, 4, 9, 4, 2, 9]

def unitvector1 (x,y):
    looplim=(len(x)+1)

    for i in range (0,looplim):
        z=i+1
        alfa = np.arccos((x[i]*x[z])+(y[i]*y[z])) / ((np.sqrt(x[i] ^ 2+y[i] ^ 2) * np.sqrt(x[z] ^ 2+y[z] ^ 2))) 

        beta =+ (180-alfa)

    return (beta)

temp=unitvector1(x,y)

print(temp)

And I am getting this error:我收到此错误:

IndexError: list index out of range IndexError:列表索引超出范围

I tried to do it with two for loops but it did not work.我试图用两个 for 循环来完成它,但它没有用。

Your help is much needed, Many thanks in advance for your help.非常需要您的帮助,非常感谢您的帮助。

Lists are indexed starting from 0, so for a list of length, say, 13, the last valid index is 12, ie, 1 less than the length.列表从 0 开始索引,因此对于长度为 13 的列表,最后一个有效索引为 12,即比长度小 1。

When you do looplim=(len(x)+1) and then for i in range (0,looplim) , the last value of i is looplim-1 which is equal to len(x) , so it's the length rather than 1 less than that.当您执行looplim=(len(x)+1)然后for i in range (0,looplim)时, i的最后一个值是looplim-1 ,它等于len(x) ,所以它是长度而不是 1少于那个。

looplim=len(x) 
for i in range(looplim-1):
alfa = np.arccos((x[i]*x[z])+(y[i]*y[z])) / ((np.sqrt(x[i] ^ 2+y[i] ^ 2) * 
np.sqrt(x[z] ^ 2+y[z] ^ 2)))  

for each iteration value of "alfa" is nan对于“alfa”的每次迭代值都是 nan

remove + 1 from looplim=(len(x)+1) and z = i+1 then run the code !从 looplim=(len(x)+1) 和 z = i+1 中删除 + 1 然后运行代码!

Okay, first u should look at your variable z.好的,首先你应该看看你的变量 z。 When i=7 z=8 and there are no eight's index element in x array.当 i=7 z=8 且 x 数组中没有八位索引元素时。 Second, idk why you try “looplim”.其次,我不知道你为什么尝试“looplim”。 If you want to do operations with n and n+1 elements in this way we can add next:如果你想以这种方式对 n 和 n+1 个元素进行操作,我们可以添加下一个:

   def unitvector1 (x,y):
      for i in range (len(x)-1):
          z=i+1
          if z==len(x)+1:
              z=0
          alfa = np.arccos((x[i]*x[z])+(y[i]*y[z])) / ((np.sqrt(x[i] ^ 2+y[i] ^ 2) * np.sqrt(x[z] ^ 2+y[z] ^ 2))) 

          beta =+ (180-alfa)

    return (beta)

But it's not working!但它不起作用! Because arccos(alpha) should have alpha<|1|因为 arccos(alpha) 应该有 alpha<|1|

If you can explain what do you want to count, maybe we can help you如果你能解释一下你想数什么,也许我们可以帮助你

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

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