python - 元组错误 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 中,但我不记得它是什么意思,也不记得我是如何修复它的。
解决方案
这是说在这条线上:
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
推荐阅读
- active-directory - AD 单值自定义属性在 powershell 中返回为多值
- c# - 数组的 GCHandle.AddrOfPinnedObject 是否总是返回指向数组第一个元素的指针?
- r - 将顶点标签放置在圆形图的外部,用于不同大小的顶点和不同大小的标签
- java - 从java中给定的一组数字中查找最大日期和时间
- java - 如何通过透明窗口从屏幕读取数据
- swift - UserDefault.standard 首选项仅正确保存约 80% 的时间
- mysql - 根据 col2 的分组值捕获 col1 的值
- c++ - 将基类指针转换为派生类指针
- ngrok - ngrok-公共网址在哪里
- scala - 将 Scio 类型的 bigquery api 与 apache-beam 一起使用时编译管道时出错