【问题标题】:Tuple Errors Python元组错误 Python
【发布时间】:2019-02-11 04:55:42
【问题描述】:

我打开 Python 并尝试运行以下脚本(顺便说一句,这个脚本是直接给我的,我没有以任何方式编辑它,因为它是除了输入用户名和密码之外的作业的一部分星号是):

import pymysql
myConnection  = pymysql.connect(host='localhost', user='****', passwd='****', db='accidents')
cur = myConnection.cursor()
cur.execute('SELECT vtype FROM vehicle_type WHERE  vtype LIKE "%otorcycle%";')
cycleList = cur.fetchall()
selectSQL = ('''
                SELECT  t.vtype, a.accident_severity
                FROM accidents_2016 AS a
                JOIN vehicles_2016 AS v ON  a.accident_index = v.Accident_Index
                JOIN vehicle_type AS t ON  v.Vehicle_Type = t.vcode
                WHERE t.vtype LIKE %s
                ORDER BY  a.accident_severity;''')
insertSQL = ('''INSERT INTO accident_medians  VALUES (%s, %s);''')

for cycle  in cycleList:
    cur.execute(selectSQL,cycle[0])
    accidents = cur.fetchall()
    quotient, remainder =  divmod(len(accidents),2)
    if  remainder:
        med_sev =  accidents[quotient][1]
    else:
        med_sev =  (accidents[quotient][1] + accidents[quotient+2][1])/2
    print('Finding median  for',cycle[0])
    cur.execute(insertSQL,(cycle[0],med_sev))
myConnection.commit()
myConnection.close()

我使用 pymysql 进行了导入,并通过命令行安装了它。此外,在阅读了由于其他错误而导致的其他一些回复后,我也安装了 pop 密码学。每次我运行脚本时,我都会收到一个新错误。现在当我运行它时,它给了我一个不同的错误:

Traceback (most recent call last):
  File "H:/School/ITS 410/Mod 8/Portfolio.py", line 22, in <module>
    med_sev =(accidents[quotient][1] + accidents[quotient+2][1])/2
IndexError: tuple index out of range

我只见过一次,它也是用 Python 编写的,但我不记得它是什么意思,也不记得我是如何修复它的。

【问题讨论】:

  • 搜索IndexError: tuple index out of range怎么样?
  • 我确实搜索过,但我找到的答案都没有对这个特定的代码有帮助。他们都认为索引和数字可能是错误的,以及 Python 是如何从 0 开始的。我已经多次切换数字,但什么也没有。还是一样的错误。
  • 复制粘贴错误的完整回溯。
  • 我用完整的回溯错误编辑了问题。

标签: python tuples


【解决方案1】:

这是说在这一行:

med_sev =(accidents[quotient][1] + accidents[quotient+2][1])/2

您正在尝试索引不存在的内容。我想它在accidents[quotient+2][1] 部分,因为这是更大的索引。这是什么意思?好吧,假设事故类似于

accidents = [[thing0, thing1], [thing2, thing3]]

现在说商是 0,所以你的代码评估事故[2][1]。这没有意义,因为事故[0] 是[thing0, thing1],事故[1] 是[thing2, thing3],但没有事故[2]。因此,当 Python 去查找它并将其分配给值 med_serv 时,它不能。您可以通过以下方式验证和调试错误:

accidents = cur.fetchall()
quotient, remainder =  divmod(len(accidents),2)
if  remainder:
    print("quotient: {}".format(quotient))
    print("accidents: {}".format(accidents))
    med_sev =  accidents[quotient][1]
else:
    print("quotient: {}".format(quotient))
    print("accidents: {}".format(accidents))
    med_sev =  (accidents[quotient][1] + accidents[quotient+2][1])/2

【讨论】:

  • 好的,谢谢。这很好地解释了事情。我能够改变商,使数字与 Python 实际寻找的相匹配。谢谢你这样解释。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-22
  • 1970-01-01
  • 1970-01-01
  • 2013-10-29
  • 2014-07-14
  • 1970-01-01
相关资源
最近更新 更多