2012-06-04 139 views
0

我目前使用下面的代码打印和格式化列表在Python

print "line 1  line2" 
for h, m in zip(human_score, machine_score): 
    print "{:5.1f}  {:5.3f}".format(h,m) 

但它可能不是很好的做法,在头只使用“行1”和“2号线”之间的空格。而且我不确定如何在每行之前添加可变数量的空格,以便我可以在底部填入“mean”和“std”,并使这两个数字与上面的列表一致。

例如,我想它打印:

 Line 1  Line 2 
     -6.0  7.200 
     -5.0  6.377 
     -10.0  14.688 
     -5.0  2.580 
     -8.0  8.421 
     -3.0  2.876 
     -6.0  9.812 
     -8.0  6.218 
     -8.0  15.873 
      7.5  -2.805 
Mean: -0.026  7.26 
Std: 2.918  6.3 

什么是这样做的最Python的方式?

回答

2

只需使用较大的字段大小,例如,对于您的标题使用:

print "{:>17} {:>17s}".format('line1', 'line2') 

,并为您的数字:

print "{:>17.1f}  {:>12.3f}".format(h,m) 

你的fo oter:

print 
print "Mean: {:11.2f}  {:12.3f}".format(-0.026, 7.26) 
print "Std : {:11.2f}  {:12.3f}".format(2.918, 6.3) 

这将使你

  line1    line2 
      -6.0    7.200 
      -5.0    6.377 
      -10.0   14.688 
      -5.0    2.580 
      -8.0    8.421 
      -3.0    2.876 
      -6.0    9.812 
      -8.0    6.218 
      -8.0   15.873 
       7.5   -2.805 

Mean:  -0.03    7.260 
Std :  2.92    6.300 

您可以根据自己的需要调整字段宽度值。

+0

完美 - 谢谢! – Zach

+0

@Zach不客气。 '.format()'非常强大,值得更好地了解:-) – Levon

1

对标题使用与数据相同的印刷技术,将标题字视为字符串。

1

你原来的问题是关于如何避免在格式字符串中的字段之间放置任意空格。你是对的,试图避免这一点。没有硬编码列的填充宽度,更具灵活性。

您可以通过使用在格式字符串外部定义的WIDTH'常量'来执行这两个操作。宽度然后作为参数传入格式函数,并插入到替换字段内的另一组大括号中的格式字符串中:{foo:>{width}}

如果要更改列宽,只需更改'constant “WIDTH

human_score = [1.23, 2.32,3.43,4.24] 
machine_score = [0.23, 4.22,3.33,5.21] 
WIDTH = 12 
mean = "Mean:" 
std = "Std:" 
print '{0:>{width}}{1:>{width}}'.format('line 1', 'line 2', width=WIDTH) 
for h, m in zip(human_score, machine_score): 
    print "{:>{width}.1f}{:>{width}.3f}".format(h,m, width=WIDTH) 

print "{mean}{:>{width1}.2f}{:>{width2}.3f}".format(-0.026, 7.26, width1=WIDTH-len(mean), width2=WIDTH, mean=mean) 
print "{std}{:>{width1}.2f}{:>{width2}.3f}".format(-2.918, 6.3, width1=WIDTH-len(std), width2=WIDTH, std=std) 

输出:

 line 1  line 2 
     1.2  0.230 
     2.3  4.220 
     3.4  3.330 
     4.2  5.210 
Mean: -0.03  7.260 
Std: -2.92  6.300 
0

使用str.rjust和str.ljust并在得分数字有关这一点。