【问题标题】:converting list of lists into a table [duplicate]将列表列表转换为表格[重复]
【发布时间】:2016-09-06 22:31:04
【问题描述】:

我有这个列表列表:

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

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

【问题讨论】:

  • 明确一点,这是 Py2 还是 Py3? print 各不相同,您的示例代码使用它的方式并没有使用任何差异来说明这一点。
  • 这是python 3.5

标签: python


【解决方案1】:

要转置表格,请使用 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   

【讨论】:

  • 最后一个条目不需要明确的字段宽度,因为它是左对齐的,如果超过宽度就会溢出。否则,是的,最好的答案。
  • 谢谢。这些#到底代表什么
  • 你点击链接了吗?数字是为内容保留的空间,以便左对齐或右对齐知道必须在左侧或右侧添加多少空格。
【解决方案2】:

你也可以玩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

【讨论】:

  • 不反对,但我认为为一个简单的问题抽出pandas 可能有点过头了。 :-)
  • @ShadowRanger 我确实考虑过,但转念一想,我认为这是一个值得提问者考虑的工具(如果不是现在,从长远来看):)
【解决方案3】:

“翻转”嵌套列表的最简单方法是使用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

【讨论】:

  • 太棒了!!!。谢谢
【解决方案4】:

已经有一个用于此的内置函数:zip

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-29
    • 1970-01-01
    • 2021-06-09
    • 2021-09-08
    • 2019-11-27
    • 2015-06-23
    • 2020-03-19
    • 2013-11-04
    相关资源
    最近更新 更多