Ошибка индекса из-за цикла for в python - PullRequest
0 голосов
/ 07 июля 2019

Как я новичок в программировании на Python.У меня проблема в цикле for с ошибкой индекса.Я прошел через предложения, которые вы мне дали.Моя проблема в том, что в цикле for ... Я не получил никакой ошибки с этим кодом ниже ...

for i in range(0,1):

Но я получил ошибку, если предел превышает, например, (0,3)

for i in range(0,3):

Ошибка:

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

Я попытался стереть эту ошибку, и я не уверен, почему эта ошибка возникает в цикле for, если пределы превышают 1.

Это мой код:

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)

Мой ожидаемый результат заключается в том, что я хочу удалить полученную ошибку, и мне интересно узнать, почему эта ошибка произошла, когда предел конца большечем один.

Ответы [ 2 ]

2 голосов
/ 07 июля 2019

Вы используете имя m для двух разных переменных в вашем коде.В верхней части файла вы используете его для создания списка имен файлов, которые вы читаете в цикле.Но позже в цикле вы переназначаете его следующей строкой:

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

Это вызывает ошибку при попытке прочитать более поздние файлы, так как новое значение m не содержит того, что ожидает код (и может не соответствовать ожидаемому размеру).

Вы должны использовать два разных имени переменной.Подобные проблемы предполагают, что было бы неплохо использовать более длинное, более описательное имя переменной, так как у вас гораздо меньше шансов столкнуться с таким типом случайного столкновения пространства имен с такими именами, как filenames и first_quaternion (или что-то еще).

Я бы также предложил использовать range(len(m)), чтобы при изменении размера списка в будущем вам не нужно было также поменять размер жестко заданного диапазона.

0 голосов
/ 07 июля 2019

изображение для выполнения этого кода. Как насчет того, чтобы попробовать заменить

for i in range(0, 5):

с

for i in range(len(m)):

EDIT: Это работает?

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)
...