2016-09-06 134 views
2

我列出這個清單:轉換列表列表變爲表

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

,我要改造成這個表:

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

我的訣竅,就是有「線「被轉換成列(即蘋果,橙子,櫻桃,下同一列香蕉)

我曾嘗試不同的選項(A):

for row in tableData: 
     output = [row[0].ljust(20)] 
      for col in row[1:]: 
      output.append(col.rjust(10)) 
      print(' '.join(output)) 

選項(B):

方法2

for i in tableData: 
    print(i[0].ljust(10)+(str(i[1].ljust(15)))+(str(i[2].ljust(15)))+ 
    (str(i[3].ljust(15))))  

沒有一個似乎解決這個問題。
在此先感謝您的任何建議。

+0

要說清楚的是,這是Py2還是Py3? 'print'不同於另一個,並且您的示例代碼使用它的方式沒有行使任何差異來說明問題。 – ShadowRanger

+0

另請參見:[Python:打印列表爲表格數據](http://stackoverflow.com/q/9535954/216074) – poke

+0

這是python 3.5 –

回答

1

「翻轉」 最簡單的方法嵌套列表是使用zip

for fruit, name, animal in zip(*tableData): 
    print(fruit.ljust(10), name.ljust(10), animal.ljust(10)) 

此打印:

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

令人驚歎的!!!謝謝 –

0

已經有這個內置函數:zip

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

要轉置表格,請使用zip-and-splat技巧。

要左或右對齊細胞,使用format spec language

>>> for row in zip(*tableData): 
...  print '{:<10}{:>7} {:<10}'.format(*row) 
...  
apples  Alice dogs  
oranges  Bob cats  
cherries Carol moose  
banana  David goose 
+0

最終條目不需要明確的字段寬度,因爲它是左對齊的,並且如果寬度超過寬度就會溢出。否則,是的,最好的答案。 – ShadowRanger

+0

謝謝。這些#代表的究竟是什麼 –

+1

您是否關注鏈接?數字是爲內容保留的空間,因此左對齊或右對齊知道必須在左側或右側添加多少間隔。 – Matthias

1

一個也玩弄pandas.DataFrame

In [22]: import pandas as pd 
In [22]: pd.DataFrame(tableData).T # .T means transpose the dataframe 
Out[22]: 
      0  1  2 
0 apples Alice dogs 
1 oranges Bob cats 
2 cherries Carol moose 
3 banana David goose 

人刪除這些煩人號將列和索引設置爲空白:

In [27]: l1, l2 = len(tableData), len(tableData[0]) 

In [28]: pd.DataFrame(tableData, index=['']*l1, columns=['']*l2).T 
Out[28]: 

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

不是downvoting,但我認爲匆忙'pandas'爲一個簡單的問題可能會過度,只是一點點。 :-) – ShadowRanger

+0

@ShadowRanger我確實考慮過這個問題,但我認爲這是一個值得考慮問題的工具(如果不是現在,從長遠來看):) –