开发者

write formatted file

I want to to write np.double to formatted file:

开发者_高级运维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()

Can this "write" row be written in a shorter way?

fid.write('%5.1f %5.1f %5.1f %5.1f %5.1f ' %(s[0],s[1],s[2],s[3],s[4]))


One way is this

In [48]: ''.join('%5.1f ' % n for n in s)
Out[48]: ' 12.0  45.0  87.0  34.0  65.0 '

Another way is

In [49]: ('%5.1f ' * len(s)) % tuple(s)
Out[49]: ' 12.0  45.0  87.0  34.0  65.0 '


fid.write(''.join(map('{:5.1f} '.format, s)))


This is the fastest way:

fid.write(''.join(map(lambda x: '%5.1f'%x , s.tolist())))

It's also worth noting that your method for reading the values in can be made much faster by doing this:

>>> import numpy as np
>>> a = '12 45 87 34 65'
>>> np.fromstring(a, sep=' ')
array([ 12.,  45.,  87.,  34.,  65.])


How about casting the doubles to strings first using a list comprehension, then creating the output row.

For example:

double_strs = ["%5.1f" % number for number in s]
fid.write( " ".join(double_strs) )


Quick and easy, my friend:

fid.write('%5.1f ' * len(s) % tuple(s))


Shortest I could come up with was:

    "%5.1f"*len(s)%s
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜