python - 输出中包含的类型“十进制”
问题描述
当我运行此代码时,我得到如下结果:
(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()
解决方案
在for item in answer:
,item
是一个tuple
。在 Python 中,如果str
对 atuple
或其他集合(如 a list
or )的调用,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 list
or )生成列表的方法tuple
。
推荐阅读
- javascript - 使用 Cypress 和不记名令牌进行身份验证
- javascript - 如何从 Flask 中的 URL 在浏览器中显示视频?
- android - 如何修复“错误:[Dagger/MissingBinding] androidx.room.RoomDatabase.Callback 不能在没有@Provides-annotated 方法的情况下提供”
- vue.js - 使用 Prettier 执行 Vue 样式指南
- spring-boot - InvalidModuleDescriptorException:在模块中找不到包 com.sun.org.apache.xerces.internal.jaxp
- string - 仅替换开头和结尾的字符串
- django - Django:只允许数据输入模型的多个字段之一
- python - 如果 x 相同,你怎么不打印?
- flutter - 列表
' 不是类型 'Map 的子类型 . 解析对模型的 api 响应时出现颤振问题 - spring-cloud-kubernetes - Spring Cloud Kubernetes:支持ConfigMap无法读取事件的失败策略