简化将列表转换为python中的表格

时间:2018-10-24 09:01:53

标签: python-3.x

这是我的代码的示例练习:

def printTable(data):
    colWidth = 8
    print(data[0][0].rjust(colWidth) + data[1][0].rjust(colWidth) + data[2][0].rjust(colWidth))
    print(data[0][1].rjust(colWidth) + data[1][1].rjust(colWidth) + data[2][1].rjust(colWidth))
    print(data[0][2].rjust(colWidth) + data[1][2].rjust(colWidth) + data[2][2].rjust(colWidth))
    print(data[0][3].rjust(colWidth) + data[1][3].rjust(colWidth) + data[2][3].rjust(colWidth))

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

如何简化printTable函数?

1 个答案:

答案 0 :(得分:0)

执行此操作的两种方法:

和熊猫一起

尝试使用pandas模块。您可以使用pandas库对Tabuler数据执行很多操作。 Pandas documentation

的链接

请参见以下示例。

import pandas as pd

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

df = pd.DataFrame(tableData)  #convert tableData to pandas dataframe
df = df.transpose()  #converting rows to columns
df.columns = ["Fruits", "Persons", "Animals"]  #adding headers to columns
print(df)

输出:

     Fruits Persons Animals
0    apples   Alice    dogs
1   oranges     Bob    cats
2  cherries   Carol   moose
3    banana   David   goose

没有熊猫

您可以简单地转置tableData并以表格格式打印它,请参见以下示例。

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

new = [list(i) for i in zip(*tableData)]   #list comprehension for transposing tableData

for i in new:
    print(*i)   #printing in table format

输出:

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