如何为下面给出的代码段添加“格式”?

问题描述 投票:1回答:2
   zip(a,b,c,d)
   with open('output.dat', 'w') as f:
   print >>f, ("%-25s %-25s %-25s %s" %(x, y, z, k))
   writer = csv.writer(f, delimiter='\t')
   writer.writerows(zip(a,b,c,d))

这段代码的输出就像

51715.505899065996  2724172.4436709681  3081070.212397085   3419080.1274145059 

我想以指数的形式写出这些数字并将其向上舍入,例如为第一个输出

5.172E4 ........

我怎样才能做到这一点 ?

python python-2.7
2个回答
5
投票

您可以使用科学记数法格式,如下所示:

num = 51715.505899065996
# .3 to keep 3 digit in fractional part
print('%.3e' % num)
print('{:.3e}'.format(num))
# 5.172e+04

对于你的场景,你可以使用地图格式,我把abcd列为清单,我不知道我是否对此有误解:

a = [51715.505899065996, 2724172.4436]
b = [2724172.4436709681, 81070.2123]
c = [3081070.212397085, 715.50589906599]
d = [3419080.1274145059, 9080.12741450]
zip(a,b,c,d)
with open('output.dat', 'w') as f:
    # print >>f, ("%-25s %-25s %-25s %s" %(x, y, z, k))
    writer = csv.writer(f, delimiter='\t')
    for A, B, C, D in zip(a,b,c,d):
        writer.writerow(map(lambda x:'{:.3e}'.format(x), (A,B,C,D)))

希望它能帮到你。


2
投票

print('%.xe' % y)print('{:.xe}'.format(y)将以科学记数法打印一个数字y,小数精度为x的地方

例如,print('%.2e' % 12)将打印1.20e+.01

© www.soinside.com 2019 - 2024. All rights reserved.