2015-06-20 81 views

回答

1

移調和使用str.join:

print("\n".join(" ".join(t) for t in zip(*tableData))) 

輸出:

apples Alice dogs 
oranges Bob cats 
cherries Carol moose 
banana David goose 

zip(*tableData)調換的數據:

[('apples', 'Alice', 'dogs'), ('oranges', 'Bob', 'cats'), ('cherries', 'Carol', 'moose'), ('banana', 'David', 'goose')] 

然後,我們只是加入從由分離的每個元組中的元素一個空格並使用換行符作爲分隔符來加入結果。

使用python3使用可以使用sep

print(*(" ".join(t) for t in zip(*tableData)), sep="\n") 
0

雖然沒有提供完全相同的輸出,你可能有興趣,看看如何csvkit處理繪製表格:

https://github.com/onyxfish/csvkit/blob/master/csvkit/utilities/csvlook.py#L40

您可以修改根據需要(例如,如果不需要,則刪除所有邊界)。說幹就幹,做到了迅速給您:

import sys 

def draw_table(rows): 
    widths = [] 

    # Calculate the width of each column 
    for row in rows: 
     for i, v in enumerate(row): 
      try: 
       if len(v) > widths[i]: 
        widths[i] = len(v) 
      except IndexError: 
       widths.append(len(v)) 

    for i, row in enumerate(rows): 

     for j, d in enumerate(row): 
      if d is None: 
       d = '' 
      sys.stdout.write(d.ljust(widths[j] + 1)) 
     sys.stdout..write('\n') 

然後,您可以只通過表格數據:

> draw_table(table_data) 

apples oranges cherries banana 
Alice Bob  Carol David 
dogs cats moose goose 
相關問題