1

I want to be able to convert a list of lists (which we can assume that the inner lists are all of equal length) into a justified table using a function.

So far I have tried the below but this doesnt justify the table.

I also need to understand what zip is doing? Can i always unpack when using *v?

Could i get an explanation of why I need to do *v to unpack out of the tuple instead of just using *Data in my code below?

def printTables(Data):
    for v in zip(*Data):
        print(*v)          

printTables(tableData)



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

Output:

apples Alice  dogs
 oranges   Bob  cats
cherries Carol moose
  banana David goose
SKhan2312
  • 297
  • 3
  • 3

2 Answers2

2

Using pandas will solve all your problem

import pandas as pd

df = pd.DataFrame(tableData).transpose()
print(df)

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

Native Python

for i, j, k in zip(*tableData):
    print('{:<12} {:<12} {:<12}'.format(i, j, k))

apples       Alice        dogs
oranges      Bob          cats
cherries     Carol        moose
banana       David        goose
N. Arunoprayoch
  • 922
  • 12
  • 20
0

Do you have to do this in native Python? Pandas DataFrames will let you deal with tabular data naturally. You can create a DataFrame form the list of lists directly:

import pandas as pd
df = pd.DataFrame(tableData)
print(df)

Zip will iterate through the ith element of each list you give it in separate arguments. E.g. zip(list1, list2, list3). The * operator will convert an iterable into different arguments. Therefore if you have a list list4 = [list1, list2, list3] you can pass the list elements as arguments to a function as zip(*list4). The print() function will print whitespace between each argument so if you pass an iterable (such as a tuple) with the * operator it will print each element in the iterable.