简体   繁体   English

列中的Python打印结果

[英]Python printing results in columns

I have been printing some of the output of my program the following way: 我已经通过以下方式打印程序的某些输出:

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)

which gives the following nice output: 这给出了以下不错的输出:

  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

But now let's say I have a number of results which is not defined, how could I write the same kind of outputs? 但是,现在让我们说我有许多未定义的结果,如何编写相同类型的输出?

Thanks. 谢谢。

You can use PrettyTable installing it with pip and show your data as follows: 您可以使用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     |
+-----------+------+------------+-----------------+

But in your case, you can use the add_column() method passing your list as parameters. 但是在您的情况下,您可以使用add_column()方法将列表作为参数传递。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM