简体   繁体   English

由于python中的for循环导致索引错误

[英]Index error due to the for-loop in python

As I am new to python programming. 因为我是python编程的新手。 I have a problem in the for loop with index error. 我在for循环中遇到索引错误的问题。 I have gone through the suggestions that you have given me. 我听了你给我的建议。 My problem is that in the for loop... I didn't get any error with this code below... 我的问题是在for循环中...下面的代码没有任何错误...

for i in range(0,1):

But I have obtained an error if the limit exceeds for example (0,3) 但是如果超出限制,例如(0,3),我得到了一个错误

for i in range(0,3):

The error is 错误是

IndexError: index 1 is out of bounds for axis 0 with size 1

I have tried to clear out this error and I am not sure that why this error occurs in the for loop if the limits exceed 1. 我试图清除此错误,但是我不确定为什么如果限制超过1,为什么在for循环中会发生此错误。

This is my code: 这是我的代码:

m=['paketone4000.dump.xlsx','paketone8000.dump.xlsx','paketone12000.dump.xlsx']
fig_name=['j4000','e8000','e12000']

fig=plt.figure(figsize=(6,6)) ##to obtain figure and dimensions of graph

for i in range(0,3):


    #ax=fig.add_subplot(111,projection='3d') ## to have a broad view of figure
    ax = fig.add_axes([0,0,1,1], projection='3d')

    #plot planes
    p = Rectangle((0,-0.7), 4.5,1.4, color="lightgrey", alpha=0.2) #plots the background frame
    ax.add_patch(p)

    art3d.pathpatch_2d_to_3d(p, z=0, zdir="z")

    j=pd.read_excel(m[i])  ##to read the excel file format
    X=j['x'] ## to import the variable on to axes from data set
    Y=j['y']
    Z=j['z']
    #ax.scatter(X,Y,Z,c='g', marker='o') ## to specify the color and shape of point(marker) of the frame

    a=j['x']##import centre of mass from excel file format
    b=j['y']
    c=j['z']

    q1=j['q1'], ##attaining quaternons from excel file format. (comma(,) transformed series to tuple)
    q2=j['q2'],
    q3=j['q3'],
    q4=j['q4'],

    m,n,o,p=np.array([q1,q2,q3,q4]) ## assigning quaternions to variables had converted tuple to float
    Rot_Mat=QtoR(m,n,o,p)

    #cuboid initialising parameters
    center = [a[0], b[0], c[0]] ##centre of the body
    length = 0.3 ##defining length, breadth, height
    width = 0.4
    height = 0.1
    side = np.zeros((8,3))  ###This numpy vector will be used to store the position of the sides

    #rotate the axes and update
    for angle in range(0, 360):
        ax.view_init(90, angle)

    cuboid(center, (length, width, height)) #to execute the defined cuboid

    plt.savefig(fig_name[i])
    plt.clf()
print("\nq1=",m,"q2=",n,"q3=",o,"q4=",p)
print('\nRotation Matrix=',Rot_Mat)
print ("\nCenter = \n",center)

My expected result is that I want to remove the error that was obtained and I am interested in to know why that error occurred when end limit is greater than one. 我的预期结果是,我想删除所获得的错误,并且我想知道为什么当结束限制大于1时会发生该错误。

You're using the name m for two different variables in your code. 您在代码中使用名称m表示两个不同的变量。 At the top of the file you use it to create a list of filenames, which you read in the loop. 在文件的顶部,您可以使用它创建一个文件名列表,您可以在循环中读取该文件名。 But later in the loop, you reassign it with this line: 但是在循环的后面,您可以使用以下这一行重新分配它:

m,n,o,p=np.array([q1,q2,q3,q4])

That causes the error when you try to read later files, as the new m value doesn't contain what the code expects (and may not be the expected size). 当您尝试读取以后的文件时,这会导致错误,因为新的m值不包含代码期望的值(并且可能不是期望的大小)。

You should use two different variable names. 您应该使用两个不同的变量名。 This kind of issue suggest that it might be a good idea to use longer, more descriptive variable name, as you are a lot less likely to have this kind of random namespace collision with names like filenames and first_quaternion (or whatever). 这种问题表明,使用更长,更具描述性的变量名可能是一个好主意,因为与诸如filenamesfirst_quaternion (或其他名称)之类的名称发生这种随机命名空间冲突的可能性要first_quaternion

I'd also suggest using range(len(m)) so that if you change the size of the list at some future time, you won't need to remember to also change the hard-coded range size. 我也建议您使用range(len(m))这样,如果您将来更改列表的大小,就不必记住也要更改硬编码的范围大小。

An image for this code execution. 此代码执行的图像 How about you try replacing 您如何尝试更换

for i in range(0, 5):

with

for i in range(len(m)):

EDIT: Does this work? 编辑:这行得通吗?

m=['paketone4000.dump.xlsx','paketone8000.dump.xlsx','paketone12000.dump.xlsx']
fig_name=['j4000','e8000','e12000']

fig=plt.figure(figsize=(6,6)) ##to obtain figure and dimensions of graph

for index, i in enumerate(m):


    #ax=fig.add_subplot(111,projection='3d') ## to have a broad view of figure
    ax = fig.add_axes([0,0,1,1], projection='3d')

    #plot planes
    p = Rectangle((0,-0.7), 4.5,1.4, color="lightgrey", alpha=0.2) #plots the background frame
    ax.add_patch(p)

    art3d.pathpatch_2d_to_3d(p, z=0, zdir="z")

    j=pd.read_excel(i)  ##to read the excel file format
    X=j['x'] ## to import the variable on to axes from data set
    Y=j['y']
    Z=j['z']
    #ax.scatter(X,Y,Z,c='g', marker='o') ## to specify the color and shape of point(marker) of the frame

    a=j['x']##import centre of mass from excel file format
    b=j['y']
    c=j['z']

    q1=j['q1'], ##attaining quaternons from excel file format. (comma(,) transformed series to tuple)
    q2=j['q2'],
    q3=j['q3'],
    q4=j['q4'],

    m2,n,o,p=np.array([q1,q2,q3,q4]) ## assigning quaternions to variables had converted tuple to float
    Rot_Mat=QtoR(m2,n,o,p)

    #cuboid initialising parameters
    center = [a[0], b[0], c[0]] ##centre of the body
    length = 0.3 ##defining length, breadth, height
    width = 0.4
    height = 0.1
    side = np.zeros((8,3))  ###This numpy vector will be used to store the position of the sides

    #rotate the axes and update
    for angle in range(0, 360):
        ax.view_init(90, angle)

    cuboid(center, (length, width, height)) #to execute the defined cuboid
    amount_of_files_to_rename=index
    new_names = [i*1000 for i in range(4*amount_of_files_to_rename)[::4]]
    for i in new_names:
        plt.savefig('packetone {}.jpg'.format(i))

    #plt.savefig(fig_name[b])
    #plt.clf()       
print("\nq1=",m2,"q2=",n,"q3=",o,"q4=",p)
print('\nRotation Matrix=',Rot_Mat)
print ("\nCenter = \n",center)

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

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