python - 使用“%”运算符将数组和字符串写入文件
问题描述
我正在尝试以某种格式(.cube 文件)导出数据;文件类型不是主要问题。
现在我必须根据行号打印不同的行格式。到目前为止一切顺利,我可以使用以下方法来做到这一点:
if line_num == 0 or line_num == 1:
# comment line
output_file.write("%s\n" % (self.comments[line_num]))
continue
if line_num == 2:
# number of total atoms, and the origin coordinates
output_file.write("%4d %.6f %.6f %.6f\n" % (self.num_atoms, self.origin[0], self.origin[1], self.origin[2]))
continue
上述工作,但我想以下列方式使用 '%' 运算符:
if line_num == 2:
# number of total atoms, and the origin coordinates
output_file.write("%4d %.6f %.6f %.6f\n" % (self.num_atoms, self.origin)
因为self.origin
是Numpy
Array 大小 1X3。
这样做时,我收到以下错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: only size-1 arrays can be converted to Python scalars
有没有办法做我想要的,而不是给数组中的每个元素。
谢谢。
解决方案
用于*self.origin
展开阵列。
>>> "%4d %.6f %.6f %.6f\n" % (num_atoms, *origin)
' 199 1.000000 2.000000 3.000000\n'
>>>
推荐阅读
- python - django web app部署在windows 10上使用apache服务器(WAMP)不显示管理站点的CSS
- latex - 表中铸造的乳胶未正确形成
- java - 捕获图像后,标签未返回,我的代码是否正确?
- c++ - 如何访问动态创建的数组?
- reactjs - 反应如何使用元掩码同时运行 2 个函数异步?
- swiftui - onTapGesture 在 SwiftUI ScrollView 中不起作用
- python - Plotly choropleth maps 仅绘制数据框的最后一个元素
- python - Odoo 14 wqweb 黑色方形渲染而不是印地语字体
- parse-platform - 解析服务器错误:未捕获的内部服务器错误。{“堆栈”:“错误”}
- typescript - 如何对模板文字类型执行重命名符号 (F2) 操作 - VSCode