将列表列表转换为表格

时间:2016-09-06 22:31:04

标签: python

我有这个列表清单:

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))))    

似乎没有解决这个问题 提前感谢任何建议。

4 个答案:

答案 0 :(得分: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   

答案 1 :(得分:1)

&#34;翻转&#34;最简单的方式嵌套列表是使用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

答案 2 :(得分: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

答案 3 :(得分:0)

已有内置函数:zip

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