我正在使用 MySQLdb 包在 python 中执行 mysql 查询。代码看起来像这样:
c=db.cursor()
c.execute("""select * from table""")
output = []
for row in c:
output.append(row[4])
where row[4]
包含我想存储在的十进制值output
list.
问题是我得到的每个值都是这样的:Decimal('XX.XX')
我想要的一切都在output
清单是 XX.XX。在剧本的最后,我的output
列表看起来像这样:
[Decimal('10.02'), Decimal('20.24'), ...]
但我需要它只包含数字,如下所示:
[10.02, 20.24, ...]
我怎么做?
Thanks!
您可以将 Decimal 对象转换为字符串:
cursor = db.cursor()
cursor.execute("""select * from table""")
output = []
for row in cursor:
output.append(str(row[4]))
或者到一个浮动:
cursor = db.cursor()
cursor.execute("""select * from table""")
output = []
for row in cursor:
output.append(float(row[4]))
将其转换为浮点数将导致其失去完整精度,因此像 20.24 这样的值将变为 20.239999999999998。
此外,如果该值是,则将其转换为浮点数将引发异常None
。为了避免这种情况,您可以使用如下辅助函数:
def convert_mysql_decimal_to_float(decimal_object):
if (decimal_object == None):
return None
else:
return float(decimal_object)
cell_value = convert_mysql_decimal_to_float(row[4])
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)