python - 修复代码中的 "index out of range"错误

标签 python list numpy

我正在运行一个代码,其中有一个列表列表。我使用以下命令访问随机索引(假设 list1 是包含列表的列表。list1 中的每个列表都具有相同的长度,因此我只是将 list2 等同于其中一个列表):

import numpy as np

x=np.random.randint(0, len(list1))
y=np.random.randint(1, len(list2))

print list1[x][y]

这显然只是我实际编写的内容的粗略近似,但它遵循相同的思路。由于某种原因,有时我会收到“索引超出范围”错误,我不知道为什么,因为 numpy randint 模块是高端独有的。为什么会这样?

此外,有没有办法编写一段代码来尝试 x 和 y 索引,看看它是否有效,如果涉及错误,只需选择两个新的随机索引? try- except block 可以解决这个问题吗?

编辑

这是我正在使用的代码:

 ridx=np.random.randint(0,len(l_bg_2))
 ridy=np.random.randint(1,len(l_bg))
 print (ridx,ridy)
 while ((bg_dict.has_key((ridx, ridy))) or (ridy==0)):
     if bg_dict.has_key((ridx, ridy)):
         ridx=np.random.randint(0,len(l_bg_2))
         ridy=np.random.randint(1,len(l_bg))
         print (ridx, ridy)
     if ridy==0:
         ridy=np.random.randint(1,len(l_bg))
         print (ridx, ridy)
 bg_dict[(ridx, ridy)]=1
 p['bg'] = (l_bg_2[ridx])[ridy]

我在打印语句中添加了以捕获哪些索引给出了索引错误。上次运行代码时,我在ridx=41、ridy=451处遇到l_bg_2[ridx][ridy]的索引错误。然后我只是运行了一条 print 语句来获取 l_bg_2[41][451] 并且它起作用了。我不知道为什么会发生这种情况,也不知道如何解决这个问题。任何帮助,将不胜感激。

最佳答案

您的y是使用list2(无论是什么)的len设置的,下限为1。因此,如果list2list1[x] 处的列表长或 list1[x] 为空,您将收到此错误。

编辑: 我刚刚注意到你问题的一部分,你询问在 try/except 中捕获这个问题。是的,IndexError 是可以捕获的,但是您应该在实现此类操作之前尝试调试实际问题。如果您不知道为什么会发生这种情况,那么仅仅抛出一个 try/except block 可能会造成巨大的性能瓶颈(取决于异常发生的可能性),甚至导致无限循环(如果是这样的话)一定)。

关于python - 修复代码中的 "index out of range"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22363566/

相关文章:

python - 在 numpy 中使用换行建立索引的最佳方法

python - 无法使用 PyQt4 中的 QProcess 放弃新进程的权限

python - 用范围内的随机数填充矩阵?

python - 使得当我从一个列表中删除一个元素时,它也会从另一个列表中删除

python - 发现 numpy 多年来百分比变化减少

python - 堆叠子图的对齐

python - 如何在 Matplotlib 中旋转表头?

原始类型的 Java List 泛型语法

android - Buildozer Numpy 运行时错误 : Broken toolchain: cannot link a simple C program

python - ctypes模块的使用