首页 > 解决方案 > 使用“%”运算符将数组和字符串写入文件

问题描述

我正在尝试以某种格式(.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.originNumpyArray 大小 1X3。

这样做时,我收到以下错误:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: only size-1 arrays can be converted to Python scalars

有没有办法做我想要的,而不是给数组中的每个元素。

谢谢。

标签: pythonnumpy

解决方案


用于*self.origin展开阵列。

>>> "%4d %.6f %.6f %.6f\n" % (num_atoms, *origin)
' 199 1.000000 2.000000 3.000000\n'
>>> 

推荐阅读