使用SQLite和Python 3.1,我希望通过HTML表格显示货币数据.接受游标作为参数的模板.因此,所有货币值必须有2个小数位,但SQLite将它们存储为浮点类型(即使结构表示十进制:-(),因此有些必须在显示之前进行转换(例如,我希望12.1显示为12.10).
代码就像这样(简化说明)......
import sqlite3
con = sqlite3.connect("mydb")
con.row_factory = sqlite3.Row
cur = con.cursor()
cur.execute("select order_no, amount from orders where cust_id=123")
for row in cur:
row['amount'] = format(row['amount'],'%.2f')
Run Code Online (Sandbox Code Playgroud)
最后一个命令抛出错误"#builtins.TypeError:'sqlite3.Row'对象不支持项目分配"
如何解决无法更改行对象值的问题?我可以将光标转换为字典列表(每行一个,例如.[{'order_no':1,'amount':12.1},{'order_no':2,'amount':6.32},... ]),然后格式化每个项目的'金额'值?如果是这样,我该怎么做?
有没有更好的解决方案来实现我的目标?任何帮助,将不胜感激.
TIA,艾伦
是的:
cur.execute("select order_no, amount from orders where cust_id=123")
dictrows = [dict(row) for row in cur]
for r in dictrows:
r['amount'] = format(r['amount'],'%.2f')
Run Code Online (Sandbox Code Playgroud)
还有其他方法,但这个方法似乎是最简单和最直接的方式.
归档时间: |
|
查看次数: |
2027 次 |
最近记录: |