首页 > 解决方案 > Python将元组转换为值

问题描述

我正在尝试使用以下方法检索表中的行数:

import postgresql

db = postgresql.open(...)
res = db.query("select count(1) from testdata")
print(res)
>>> (10,)

我怎样才能打印10

标签: pythonpostgresqliterable-unpacking

解决方案


db.query()返回查询结果的元组,即使查询只寻找一个值。我们可以使用以下方法遍历响应的结果next

import postgresql

db = postgresql.open(...)
res = db.query("select count(1) from testdata")
count_result = res.next()

(请参阅使用 Python 进行数据整理p.212)。


替代方法:

count_result = res[0] # first argument of res is the count
count_result, *_ = db.query("select count(1) from testdata") 
# first argument assigned to `count_result`
# subsequent arguments unassigned

推荐阅读