【问题标题】:Converting tuple to int in python在python中将元组转换为int
【发布时间】:2019-05-15 02:10:16
【问题描述】:

我有一个返回元组的查询,我试图将第一个值从该元组转换为 int,但它总是给我这个错误: TypeError: int() argument must be a string, a bytes-like object or a number, not 'tuple'

我不明白为什么要这样做,因为返回的值看起来像这样:[(25,)]

代码如下:

cursor.execute("SELECT temp FROM temperatures WHERE datetimetest = ?", [datenow])
    currentTemp = cursor.fetchall()
    print(currentTemp) # this gives me [(25,)]
    convertedTemp = int(currentTemp[0])

【问题讨论】:

  • [(25,)] 是一个列表,其中包含一个 int 的元组(1 个长度的元组)。不要尝试转换,只需使用var[0][0] 访问它

标签: python sql type-conversion


【解决方案1】:

因为[(25,)] 实际上是列表内元组中的一个 int - 所以获取该 int 的正确调用应该是 currentTemp[0][0]

【讨论】:

  • 哦,现在我明白了!我对python有点陌生,所以我不知道:(谢谢你帮助我!
【解决方案2】:

您可以将元组列表转换为整数列表

query = "some query that gets list of integers"
cursor.execute(query)
values = cursor.fetchall()

# values now looks like : [(1,), (2,), (3,)] 

i = 0
for v in values:
    values[i] = v[0]
    i += 1

# values now looks like : [1, 2, 3] 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-03
    • 1970-01-01
    • 2017-02-11
    相关资源
    最近更新 更多