首页 > 解决方案 > 元组错误 Python

问题描述

我打开 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 中,但我不记得它是什么意思,也不记得我是如何修复它的。

标签: pythontuples

解决方案


这是说在这条线上:

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

推荐阅读