Skip to main content
 首页 » 编程设计

python之如何为下面给出的代码添加 "format"

2025年05月04日13zengkefu

   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 ........ 

我该怎么做?

请您参考如下方法:

你可以使用科学记数法,像这样:

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

对于你的场景,你可以使用map format,我对待a, b, c, d 作为列表,我不知道我是否对此有误解:

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))) 

希望对你有帮助。