【问题标题】:Python to convert tuple to valuePython将元组转换为值
【发布时间】:2018-05-31 14:29:47
【问题描述】:

我正在尝试检索表中的行数 与:

import postgresql

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

如何只打印10

【问题讨论】:

  • print(res[0]) 你看到的是返回的tuple 而不是list
  • @EdChum,谢谢,我会更正主题
  • 或者,如果你想避免一开始就有一个元组,你可以在赋值时用res, = db.query("...")解包它(注意res后面的逗号)。
  • @jdehesa 是的,它有效,但如何?你能解释一下还是给个链接?谢谢您,非常感谢您的帮助!
  • 还有一个。我如何将其标记为已解决? )

标签: python postgresql iterable-unpacking


【解决方案1】:

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

import postgresql

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

(见Data Wrangling with 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

【讨论】:

    猜你喜欢
    • 2017-06-20
    • 2021-09-12
    • 2011-03-13
    • 1970-01-01
    • 1970-01-01
    • 2012-04-21
    • 1970-01-01
    • 2016-04-22
    • 1970-01-01
    相关资源
    最近更新 更多