Python打印结果列

时间:2015-12-03 13:41:36

标签: python printing repr

我一直按以下方式打印我程序的一些输出:

a=[1,2,3]
b=[10,20,30]
c=[101,201,301]
d=[1010,2010,3010]

results = {'a':a,'b':b,'c':c,'d':d}

print str("First result:  ").center(20), str("Second result:  ").center(20), str("Third result:  ").center(20), str("Fourth result:  ").rjust(20)
print
for i in xrange(len(results)):
    print repr(float("{0:.2f}".format(results['a'][i]))).center(20),\
          repr(float("{0:.2f}".format(results['b'][i]))).center(20),\
          repr(float("{0:.2f}".format(results['c'][i]))).center(20),\
          repr(float("{0:.2f}".format(results['d'][i]))).center(20)

给出了以下不错的输出:

  First result:        Second result:       Third result:          Fourth result:

        1.0                  10.0                101.0                1010.0
        2.0                  20.0                201.0                2010.0
        3.0                  30.0                301.0                3010.0

但现在让我说我有一些未定义的结果,我怎么能写出相同类型的输出呢?

感谢。

1 个答案:

答案 0 :(得分:2)

您可以PrettyTable使用pip进行安装,并按如下方式显示您的数据:

x = PrettyTable(["City name", "Area", "Population", "Annual Rainfall"])
x.align["City name"] = "l" # Left align city names
x.padding_width = 1 # One space between column edges and contents (default)
x.add_row(["Adelaide",1295, 1158259, 600.5])
x.add_row(["Brisbane",5905, 1857594, 1146.4])
x.add_row(["Darwin", 112, 120900, 1714.7])
x.add_row(["Hobart", 1357, 205556, 619.5])
x.add_row(["Sydney", 2058, 4336374, 1214.8])
x.add_row(["Melbourne", 1566, 3806092, 646.9])
x.add_row(["Perth", 5386, 1554769, 869.4])
print x



+-----------+------+------------+-----------------+ 
| City name | Area | Population | Annual Rainfall |
+-----------+------+------------+-----------------+
| Adelaide  | 1295 |  1158259   |      600.5      |
| Brisbane  | 5905 |  1857594   |      1146.4     |
| Darwin    | 112  |   120900   |      1714.7     |
| Hobart    | 1357 |   205556   |      619.5      |
| Melbourne | 1566 |  3806092   |      646.9      |
| Perth     | 5386 |  1554769   |      869.4      |
| Sydney    | 2058 |  4336374   |      1214.8     |
+-----------+------+------------+-----------------+

但在您的情况下,您可以使用add_column()方法将列表作为参数传递。