首页 > 解决方案 > 输出中包含的类型“十进制”

问题描述

当我运行此代码时,我得到如下结果:

(3205, Decimal('1.000'))(28802, Decimal('7.000'))(3106, Decimal('1.000'))(3173, Decimal('5.000')). 

我不想看到输出中包含“十进制”字,我该如何避免这种情况?

cur.execute('SELECT tk_product_ord, SUM(tk_qty_ord) as qty_required '
        'FROM table1 WHERE tk_date = 15047 AND tk_prod_group = 11 '
        'GROUP BY tk_product_ord;')

answer = cur.fetchall()

file = open("test_data_output.txt")
with open("test_data_output.txt", "w") as line:
    for item in answer:
        line.write("%s\n" % str(item))
    file.close()

标签: pythonpostgresql

解决方案


for item in answer:item是一个tuple。在 Python 中,如果str对 atuple或其他集合(如 a listor )的调用,dict则集合中的项目将显示为它们的repr而不是它们的str

要获得所需的输出,请调用str的每个元素item并在结果上调用str.join

with open("test_data_output.txt", "w") as line:
    for item in answer:
        output = ' '.join([str(elem) for elem in item])
        line.write("%s\n" % output)

该表达式[str(elem) for elem in item]是一个列表推导式,一种从现有序列对象(如 a listor )生成列表的方法tuple


推荐阅读