我不知道为什么我得到一个类型

2024-09-24 02:24:20 发布

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

我使用sqlite3游标计算百分比变化的代码如下:

cursor3.execute('SELECT total FROM userTotals WHERE userid = :userid ORDER BY date DESC LIMIT 1', {'userid': userid})

for value in cursor3:
    total = value

percentageChange = ((float(valueList['Total']) - total)/abs(total))*100

在这种情况下,float(valueList['Total'])没有问题,我从数据库中收集的总数是REAL类型的,sqlite命令返回的当前值是1.0。为什么会出现以下错误?你知道吗

    percentageChange = ((float(valueList['Total']) - total)/abs(total))*100
TypeError: unsupported operand type(s) for -: 'float' and 'tuple'

Tags: 代码forexecutevalueabsfloatsqlite3total
3条回答

似乎total持有一个类型为tuple的值。我建议您打印查询返回的数据以查看实际包含的数据。 print(cursor3)print(value)应该可以。你知道吗

您可能需要从cursor3中分离出两个不同的变量。我希望它是数据和查询相关的元数据,比如查询的成功状态或者类似的东西。(不过,最后一部分不太清楚,我自己也没试过。)

我相信您的游标正在返回一个元组,而值正在引用元组对象。你知道吗

您可以使用如下打印语句来确认这一点:

for value in cursor3:
    print(value)

检查你到底得到了什么。你知道吗

另外,为什么不尝试使用以下语法:

for row in cursor3.execute('SELECT total FROM userTotals WHERE userid = :userid ORDER BY date DESC LIMIT 1', {'userid': userid}):
    your_formula_here

查询返回一堆行。包含单个值的行与仅包含该值的行不同(例如1 != [1]),因此需要从中提取单个字段:

cursor3.execute('SELECT ... LIMIT 1', {'userid': userid})
total = cursor3.fetchone()[0]

或:

cursor3.execute('SELECT ... LIMIT 1', {'userid': userid})
(total,) = cursor3.fetchone()

# total, = cursor3.fetchone() also works but it always looks funny to me

以上格式适用于具有多列的结果:

cursor3.execute('SELECT a, b ... LIMIT 1', {'userid': userid})
total1, total2 = cursor3.fetchone()

相关问题 更多 >