类型错误:元组索引必须是整数,而不是s

2024-09-24 00:29:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从数据库中提取数据并将它们分配给不同的列表。 这个特定的错误给了我很多麻烦“TypeError:元组索引必须是整数,而不是str” 我试着把它转换成浮子等,但没有成功。

代码如下

conn=MySQLdb.connect(*details*)
cursor=conn.cursor()
ocs={}
oltv={}
query="select pool_number, average_credit_score as waocs, average_original_ltv as waoltv from *tablename* where as_of_date= *date*"
cursor.execute(query)
result=cursor.fetchall()

for row in result:
 print row
 ocs[row["pool_number"]]=int(row["waocs"])
 oltv[row["pool_number"]]=int(row["waoltv"])

打印语句的输出示例如下:

('MA3146', 711L, 81L)
('MA3147', 679L, 83L)
('MA3148', 668L, 86L)

这正是我得到的错误:

ocs[row["pool_number"]]=int(row["waocs"])
TypeError: tuple indices must be integers, not str

任何帮助都将不胜感激!谢谢大家!


Tags: numberas错误connquerycursorintrow
3条回答

就像错误所说的,row是一个元组,因此不能执行row["pool_number"]。您需要使用索引:row[0]

TL;DR:在MySQLdb.connect的末尾添加参数cursorclass=MySQLdb.cursors.DictCursor


我有一个工作代码和数据库移动,我必须改变主机/用户/通行证。更改后,我的代码停止工作,并开始出现此错误。仔细检查后,我将连接字符串复制粘贴到一个有额外指令的地方。旧的代码读起来像:

 conn = MySQLdb.connect(host="oldhost",
                        user="olduser",
                        passwd="oldpass",
                        db="olddb", 
                        cursorclass=MySQLdb.cursors.DictCursor)

替换为:

 conn = MySQLdb.connect(host="newhost",
                        user="newuser",
                        passwd="newpass",
                        db="newdb")

最后的参数cursorclass=MySQLdb.cursors.DictCursor使python允许我使用列名作为索引来访问行。但糟糕的复制粘贴消除了这一点,产生了错误。

因此,作为已经提出的解决方案的替代方案,您还可以添加此参数,并按照最初需要的方式访问行。^_^我希望这能帮助别人。

问题是如何访问row

特别是row["waocs"]row["pool_number"]ocs[row["pool_number"]]=int(row["waocs"])

如果您查找找到的fetchall()official-documentation

The method fetches all (or all remaining) rows of a query result set and returns a list of tuples.

因此,您必须使用row[__integer__]访问行的值,如row[0]

相关问题 更多 >