写格式化文件
我想把 np.double
写入一个格式化的文件:
import numpy as np
a='12 45 87 34 65';
s=np.double(a.split())
fid=open('qqq.txt','wt')
fid.write('%5.1f %5.1f %5.1f %5.1f %5.1f ' %(s[0],s[1],s[2],s[3],s[4]))
fid.close()
这个“写入”的代码能不能写得更简洁一些呢?
fid.write('%5.1f %5.1f %5.1f %5.1f %5.1f ' %(s[0],s[1],s[2],s[3],s[4]))
6 个回答
0
这是最快的方法:
fid.write(''.join(map(lambda x: '%5.1f'%x , s.tolist())))
另外,值得一提的是,你读取值的方法可以通过这样做变得更快:
>>> import numpy as np
>>> a = '12 45 87 34 65'
>>> np.fromstring(a, sep=' ')
array([ 12., 45., 87., 34., 65.])
1
fid.write(''.join(map('{:5.1f} '.format, s)))
当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。
6
一种方法是这样的
In [48]: ''.join('%5.1f ' % n for n in s)
Out[48]: ' 12.0 45.0 87.0 34.0 65.0 '
另一种方法是
In [49]: ('%5.1f ' * len(s)) % tuple(s)
Out[49]: ' 12.0 45.0 87.0 34.0 65.0 '