python - 如何从查询结果中去除 "Decimal"

标签 python python-3.x

<分区>

我使用以下代码从 PostgreSQL 查询得到结果:

cur = con.cursor()
cur.execute("""SELECT to_char(tt.service_date,'yyyy-mm-01') AS txn_month,
        SUM (tt.customer) AS customer,SUM (tt.tour) AS tour,
        SUM (tt.distancetraveled) AS distancetraveled
    FROM
        tbl_travel as tt
    GROUP BY
        txn_month""")
rows = cur.fetchall()

我的查询结果是这样的:

[('2016-01-01', Decimal('11.0909090909090909'), Decimal('3.7272727272727273'), 58.5354545454545),
 ('2016-02-01', Decimal('11.6666666666666667'), Decimal('4.0000000000000000'), 74.8766666666667)]

我需要删除值前面的“Decimal”字符串并得到如下结果:

[('2016-01-01', '11.0909090909090909', '3.7272727272727273','58.5354545454545'),
 ('2016-02-01', '11.6666666666666667', '4.0000000000000000','74.8766666666667')]

最佳答案

使用list comprehensions ,

from decimal import Decimal

lists = [('2016-01-01', Decimal('11.0909090909090909'), Decimal('3.7272727272727273'), 58.5354545454545),
         ('2016-02-01', Decimal('11.6666666666666667'), Decimal('4.0000000000000000'), 74.8766666666667)]

results = [tuple(str(item) for item in t) for t in lists]

print(results)
[('2016-01-01', '11.0909090909090909', '3.7272727272727273', '58.5354545455'), 
 ('2016-02-01', '11.6666666666666667', '4.0000000000000000', '74.8766666667')]

关于python - 如何从查询结果中去除 "Decimal",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40802371/

相关文章:

python - 使用手套中的训练数据为您的数据集获取词嵌入

python - 获得跨越networkx.Graph中两组节点的边的快速方法

python - mustache 被定义为 1.5* IQR,python seaborn boxplot 中的两个 mustache 怎么会不同呢?

python使用内部类作为静态类变量奇怪的行为

python - Django错误: TypeError: __init__() got an unexpected keyword argument 'attrs'

python - 如何合并这两列? Pandas

python - 无法将 extra_option 与路径 django 一起使用

python - 如何组合/加速多个 API 调用以提高性能?

python - 如何将代码分配给条形图中的 xlabel

python-3.x - 您需要在 brew 切换之前/之后运行 brew unlink/brew link 吗?