【问题标题】:Python mysql fetchall() returns additional charactersPython mysql fetchall() 返回附加字符
【发布时间】:2020-03-06 07:57:34
【问题描述】:

我正在尝试从表中检索值以用于计算。下面的代码

mycursor = mydb.cursor()

mycursor.execute("SELECT number FROM info")

rows = mycursor.fetchall()

print (rows)

这会返回这个列表

[(Decimal('30.00'),), (Decimal('66.00'),), (Decimal('72.00'),)]

我怎样才能只在列表或元组中检索数值

[30.00, 66.00, 72.00]

【问题讨论】:

    标签: python mysql fetchall


    【解决方案1】:

    mydb 中的原始数据类型可能是 Decimal 对象。 因此,您可以在 MySQL 查询或 python 代码中转换数据类型。

    1) MySQL 中的案例:

    SELECT CAST(number AS DOUBLE) FROM info
    

    但此代码将获取的行返回为 [(30.00,), (66.00,), (72.00,)] 因为元组代表查询结果的列。

    2)python代码中的案例:

    converted_rows = list(map(lambda row:float(row[0]), rows))
    

    它将返回[30.00, 66.00, 72.00] 列表。

    【讨论】:

      猜你喜欢
      • 2014-04-23
      • 2019-09-25
      • 1970-01-01
      • 2012-12-21
      • 1970-01-01
      • 1970-01-01
      • 2022-01-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多