python - Python将元组转换为值
问题描述
我正在尝试使用以下方法检索表中的行数:
import postgresql
db = postgresql.open(...)
res = db.query("select count(1) from testdata")
print(res)
>>> (10,)
我怎样才能打印10
?
解决方案
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
推荐阅读
- ruby-on-rails - Rails:简洁地打印变量名称和
标签(如果存在) - node.js - 如何使用request-promise从nodejs中的HTTP GET请求获取字符串响应到变量
- python - 如何在没有全局变量的情况下将值传递给回调以进行匿名化?
- selenium - 如何解决 Selenium ChromeDriver Timed out 从渲染器异常接收消息
- ruby-on-rails - 如何访问定制的狂欢模型
- python - 如何使用 PYTHON 代码将 Markdown 表的标题行内容向左对齐,所有其他行内容向右对齐
- python - 当有很多选择时如何提高我的熊猫效率
- powershell - 点源脚本在第二次运行时未引用当前目录
- mysql - 如何在 mysql 选择查询中选择静态值?
- java - 切换到 Java 10 时出错