簡體   English   中英

列中的Python打印結果

[英]Python printing results in columns

我已經通過以下方式打印程序的某些輸出:

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

但是,現在讓我們說我有許多未定義的結果,如何編寫相同類型的輸出?

謝謝。

您可以使用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()方法將列表作為參數傳遞。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM