python - python中不断捕获异常

标签 python python-3.x

我需要在索引列表时不断捕获异常抛出 IndexError 异常,例如:

l = []
while((l[3]) throws IndexError):
    //Add more data to the list
    l += [3]

如何在不嵌套嵌套 try/catch block 的情况下继续检查方法调用是否引发异常?

最佳答案

这取决于您想用什么来扩展您的列表。假设“无”,你可以这样做:

l = []
while True:
  try:
    l[3] = 'item'
    break
  except IndexError:
    l.extend([None])

print l # [None, None, None, 'item']

关于python - python中不断捕获异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22451472/

相关文章:

python - 编写 Python 音乐流媒体

python - Python 3.2 中的暴力破解脚本

python - 解析列表以获取精确值

macos - OS X - 谁能解释为什么我在安装 ipython3 后在我的 .pythonrc.py 文件中收到操作系统错误,或者给我一个比这更强大的解决方案?

python - TensorFlow 传递梯度不变

python - 当 tastypie 连接非 ORM 源​​时,如何返回 404?

python - 如何从现有数据框的某一列的前 10 名创建新的 pandas 数据框

python - 如何正确地将 PyTZ 添加到 Google App Engine 应用程序?

python - 值错误 : Length mismatch: Expected axis has 0 elements while creating hierarchical columns in pandas dataframe

python - 如何更改 python 3 pandas.DataFrame 的表形式?