【问题标题】:Index error due to the for-loop in python由于python中的for循环导致的索引错误
【发布时间】:2019-11-17 10:21:40
【问题描述】:

因为我是 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

我已尝试清除此错误,但我不确定如果限制超过 1,为什么会在 for 循环中出现此错误。

这是我的代码:

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)

我的预期结果是我想删除获得的错误,并且我有兴趣知道为什么当结束限制大于一时会发生该错误。

【问题讨论】:

  • m 在索引012 处只有三个元素,当您使用j=pd.read_excel(m[a])a 时,您期望m[4] 是什么? 4?
  • 即使是a in range(1) 这个center = [a[0], b[0], c[0]] throw TypeError
  • 是的,我已将for i in range(0,3): 更改为中心center = [a[i],b[i],c[i]],即使通过index error
  • abc 列表/元组?
  • 如果我想要m[4],那么我会将for循环的范围更改为for i in range (0,5):。这是您期待的答案还是其他什么?

标签: python for-loop index-error


【解决方案1】:

此代码执行的image。你换个试试怎么样

for i in range(0, 5):

for i in range(len(m)):

编辑: 这行得通吗?

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)

【讨论】:

  • 很抱歉,即使同样的错误File "D:/Thesis/Excel/New1-all.py", line 143, in <module> j=pd.read_excel(m[i]) ##to read the excel file format IndexError: index 1 is out of bounds for axis 0 with size 1。发生错误的任何其他建议。
  • 可能是你的exel有问题?
  • 如果是这种情况,那么我不应该获取 excel 的第一个文件的图像。在此我正在获取m[0] 的图像
  • 错误在....File "D:/Thesis/Excel/New1-all.py", line 162, in <module> center = [a[index], b[index], c[index]] ##centre of the bodyFile "pandas\_libs\hashtable_class_helper.pxi", line 964, in pandas._libs.hashtable.Int64HashTable.get_item KeyError: 1。我已将您的代码中的行更改为 plt.savefig(fig_name[index]) plt.clf()
  • 亲爱的,对这个问题还有什么建议吗?
【解决方案2】:

您将名称 m 用于代码中的两个不同变量。在文件的顶部,您使用它来创建文件名列表,您可以在循环中读取该列表。但是在循环的后面,你用这一行重新分配它:

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

当您尝试读取以后的文件时,这会导致错误,因为新的 m 值不包含代码预期的内容(并且可能不是预期的大小)。

您应该使用两个不同的变量名。这类问题表明使用更长、更具描述性的变量名称可能是个好主意,因为您不太可能与 filenamesfirst_quaternion (或其他)这样的名称发生这种随机命名空间冲突.

我还建议使用range(len(m)),这样如果您在未来某个时间更改列表的大小,您就不需要记住还要更改硬编码的范围大小。

【讨论】:

  • 是的,可能是这样。正如您现在在代码中看到的那样,我已将 m 编辑为数据包。此时,我收到错误center = [a[i], b[i], c[i]] ##centre of the body File "pandas\_libs\hashtable_class_helper.pxi", line 964, in pandas._libs.hashtable.Int64HashTable.get_item KeyError: 1 –
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-13
  • 2020-09-09
  • 2018-12-29
  • 1970-01-01
  • 2021-09-02
  • 1970-01-01
相关资源
最近更新 更多