2016-02-16 18 views
0

我正在創建一個包含4列的表。在python中創建數據表

在我的程序中,我已經形成了一份信息清單。 我可以將數據分成4塊(每行),或爲每一列創建一個單獨的列表。

是否有可能在python程序中創建一個包含這些值的表,還是需要先導出數據?

編輯:對於Fauxpas

Column 1    Column 2    Column 3    Column 4    

       10      10      10      30 

       20      10      10      40 

       20      20      10      50 
+0

什麼樣的表是你在說什麼?文本,數據庫,HTML? – Pedru

+0

只是一個可以顯示數字給用戶,很容易理解。 4列x 5行@Pedru – mrzippy01

+0

好的,你可以自己來做,比如@Fauxpas suggetst,或者你可以使用一些類似[texttable](https://github.com/foutaise/texttable/)的庫,還有很多其他的。 – Pedru

回答

1

如果你正在尋找做基礎,你可以使用.format方法,閱讀文檔瞭解格式化,所以你可以指定每列

的間距這段文字

your_list = ['bread', 'milk', 'sugar', 'tea'] 

print("{0:20} {1:20} {2:20} {3:20}\n".format('Column 1', 'Column 2', 'Column 3', 'Column 4')) 
print("{0:20} {1:20} {2:20} {3:20}\n".format(your_list[0], your_list[1], your_list[2], your_list[3])) 

返回:

Column 1    Column 2    Column 3    Column 4    

bread     milk     sugar     tea 

有了一個for循環示例越來越近了,你可能會想要做什麼:

your_list = ['bread', 'milk', 'sugar', 'tea', 'eggs', 'shampoo', 'clothes', 'tiger', 'beads', 'washing machine', 'juice', 'mixed herbs'] 

print("{0:20} {1:20} {2:20} {3:20}\n".format('Column 1', 'Column 2', 'Column 3', 'Column 4')) 
i = 0 
for x in range(0, 3): 
    print("{0:20} {1:20} {2:20} {3:20}\n".format(your_list[i], your_list[i + 1], your_list[i + 2], your_list[i + 3])) 
    i += 4 

輸出:

Column 1    Column 2    Column 3    Column 4    

bread     milk     sugar     tea     

eggs     shampoo     clothes     tiger    

beads     washing machine   juice     mixed herbs  

編輯:

your_list = ['10', 10, '20', 20] 
print("{0:20} {1:20} {2:20} {3:20}\n".format('Column 1', 'Column 2', 'Column 3', 'Column 4')) 
print("{0:20} {1:20} {2:20} {3:20}\n".format(your_list[0], your_list[1], your_list[2], str(your_list[3]))) 

輸出:

Column 1    Column 2    Column 3    Column 4    

10          10 20      20  

如果轉換在列表中的整數由最後的元素在使用STR(我的格式聲明證實字符串)方法則不會出現這種情況:)

str(your_list[3]) 

https://docs.python.org/2/library/string.html

+0

列將不會對齊,除非它們具有完全相同的寬度。 – Selcuk

+0

添加編輯以給出格式化示例 – Fauxpas

+0

您可以發佈您的格式聲明嗎?確保在代碼前放置4個空格並檢查預覽輸出。 通過編輯您的原創帖子來實現此效果 – Fauxpas