将输出文件值减少到2位小数

时间:2014-04-16 13:44:17

标签: python python-2.7 file-io string-formatting

我的下面包含整个值并将它们输出到另一个文件中。

with open('candidatevalues2.txt', 'w') as outfile:
    outfile.write('plate mjd fiberid FWHM erFWHM loglum loglumerr logBHmass logBhmasserr  ksvalue pvalue\n')
for i in range(9):
    with open('candidatevalues2.txt', 'a') as outfile:
        dmpval= stats.ks_2samp(y_real[i], yfit[i])
        outfile.write('{0} {1} {2} {3} {4} {5} {6} {7} {8} {9} {10}\n'.format(plate[i], mjd[i], fiberid[i], fwhm[i], fwhmer[i], loglum[i], loglumerr[i], logbhmass[i], logbhmasserr[i], dmpval[0], dmpval[1]))

文件的前几行显示为:

plate mjd fiberid FWHM erFWHM loglum loglumerr logBHmass logBhmasserr ksvalue pvalue

590 52057 465 1710.58526651 115.154250367 42.0681732777 0.070137615974 6.81880343617 0.15451686304 0.0909090909091 0.970239478143

1793 53883 490 1736.15809558 144.074772803 40.160433977 0.0736271164581 5.7828225787 0.13016470738 0.0909090909091 0.970239478143

648 52559 335 1530.9128304 153.965617385 40.8584948115 0.110687643929 6.05420009544 0.155678567881 0.0909090909091 0.970239478143

我想知道如何将所有值减少到只有2位小数?

1 个答案:

答案 0 :(得分:1)

我知道,在python中学习使用.format需要一段时间,格式规范有点隐藏。

使用python字符串format方法

的简短课程

以下是几次迭代,如何修改代码:

原始代码:

 outfile.write('{0} {1} {2} {3} {4} {5} {6} {7} {8} {9} {10}\n'.format(plate[i], mjd[i], fiberid[i], fwhm[i], fwhmer[i], loglum[i], loglumerr[i], logbhmass[i], logbhmasserr[i], dmpval[0], dmpval[1]))

简化以使解释更容易和更短:

 outfile.write('{0} {1} {2}\n'.format(plate[i], dmpval[0], dmpval[1]))

单独格式化模板和渲染:

 templ = '{0} {1} {2}\n'
 outfile.write(templ.format(plate[i], dmpval[0], dmpval[1]))

指定2位小数格式:

 templ = '{0:.2f} {1:.2f} {2:.2f}\n'
 outfile.write(templ.format(plate[i], dmpval[0], dmpval[1]))

现在你将拥有,你所要求的。

使用templ.format(**locals())成语

如果您希望通过名称,名称和属性(使用点表示法)或名称和常量正索引直接提供变量内容,您可以直接在模板中使用它们并使用技巧,即本地( )返回本地可用变量的字典,**locals()使它们在调用中可用作关键字变量:

 plate_i = plate[i]
 templ = '{plate_i:.2f} {dmpval[0]:.2f} {dmpval[1]:.2f}\n'
 outfile.write(templ.format(**locals()))

但是,你知道,这对于另一个变量指定的索引不起作用,这就是我必须引入新变量plate_i的原因。