【问题标题】:Python : IndexError: tuple index out of rangePython:IndexError:元组索引超出范围
【发布时间】:2014-08-06 20:26:00
【问题描述】:

在 python 中我有这个代码

if record[0][1]:

问题是......当mysql没有返回任何东西时......

record[0][1]

没有数据..

此 python 代码失败:

if record[0][1]:
IndexError: tuple index out of range

我只是希望它继续执行“else”语句,或者只是将这个 if 语句视为 .. 考虑到这一点是无效的

record[0][1]

没有价值。或数据..(从 mysql 传入的东西)

【问题讨论】:

  • 你总是可以try: ... except IndexError: ...

标签: python python-2.6


【解决方案1】:
try:
    if record[0][1]:
        # Do stuff
except IndexError:
    pass

【讨论】:

  • 这看起来像在 Python 中的反模式,您只需访问元组 - 由 try/except 包围 - 但实际上不测试数据是否存在。请求宽恕而不是许可。
  • 我也收到这样的错误stackoverflow.com/questions/46945860/…
【解决方案2】:

您可以使用try...except 或对外部元组使用短路检查。

if len(record) > 0 and len(record[0]) > 1 and record[0][1]:

【讨论】:

    猜你喜欢
    • 2012-03-04
    • 1970-01-01
    • 1970-01-01
    • 2013-06-26
    • 1970-01-01
    • 2021-10-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多