Printing Lists as Tabular Data

Printing Lists as Tabular Data

Some ad-hoc code:

row_format ="{:>15}" * (len(teams_list) + 1)
print(row_format.format("", *teams_list))
for team, row in zip(teams_list, data):
print(row_format.format(team, *row))

This relies on str.format() and the Format Specification Mini-Language.

Print list in table format in python

I'll show you a 3-list analog:

>>> l1 = ['a', 'b', 'c']
>>> l2 = ['1', '2', '3']
>>> l3 = ['x', 'y', 'z']
>>> for row in zip(l1, l2, l3):
... print ' '.join(row)

a 1 x
b 2 y
c 3 z

python Printing a list in a tabular format without modules

With some print and some formatting

values = [2, '1234', 'E', 2.0, 2.71,
6, '0800', 'U', 2.34, 20.89]

cols = ["EntryNo", "PumpNo", "Time", "FType", "LPrice", "FAmount"]
print(*cols)
print("-" * len(" ".join(cols))) # optional

for idx, i in enumerate(range(0, len(values), 5), start=1):
print("{:<7d} {:<6d} {:<4s} {:<5s} {:<6.2f} {} ".format(idx, *values[i:i + 5]))
EntryNo PumpNo Time FType LPrice FAmount
----------------------------------------
1 2 1234 E 2.00 2.71
2 6 0800 U 2.34 20.89


With module pandas

You can use pandas, you'll easily have an nice output, with to_markdown for example

import pandas as pd

values = [2, '1234', 'E', 2.0, 2.71,
6, '0800', 'U', 2.34, 20.89]

df = pd.DataFrame([[idx, *values[i:i + 5]] for idx, i in enumerate(range(0, len(values), 5), start=1)],
columns=["EntryNo", "PumpNo", "Time", "FType", "LPrice", "FAmount"])

print(df.to_markdown(index=False))
|   EntryNo |   PumpNo |   Time | FType   |   LPrice |   FAmount |
|----------:|---------:|-------:|:--------|---------:|----------:|
| 1 | 2 | 1234 | E | 2 | 2.71 |
| 2 | 6 | 0800 | U | 2.34 | 20.89 |

Print List of Lists in Neat Columns/Table

Using list comprehensions for a side effect is bad style: you create a full list (wich takes time & memory) that gets thrown away afterwards - use simple loops.

You need to calculate the length of each word (in each column). Getting the maximum length of your words is simple:

data = [['FirstFirst', 'FirstSecond', 'FirstThird'],
['SecondFirst', 'SecondSecond', 'SecondThird'],
['ThirdFirst', 'ThirdSecond', 'ThirdThird'],
['foo', 'verylongwordinsidehere', 'bar', ]] # changed to a longer one


# get max word length
max_len = max(len(i) for j in data for i in j)

# do not use list comp for printing side effect - use a simple loop
for inner in data:
for word in inner:
print(f"{word:{max_len}}",end=" | ") # and format the length into it
print()

to get

FirstFirst             | FirstSecond            | FirstThird             | 
SecondFirst | SecondSecond | SecondThird |
ThirdFirst | ThirdSecond | ThirdThird |
foo | verylongwordinsidehere | bar |

This looks kinda ugly, would be better if you only got the max length per column imho:

# transpose the list, get the max of each column and store in as dict[column]=legnth
col_len = {i:max(map(len,inner)) for i,inner in enumerate(zip(*data))}

# print(col_len) # {0: 11, 1: 22, 2: 11}

# print using the column index from enumerate to lookup this columns lenght
for inner in data:
for col,word in enumerate(inner):
print(f"{word:{col_len[col]}}",end=" | ")
print()

to get a column-width adjusted output:

FirstFirst  | FirstSecond            | FirstThird  | 
SecondFirst | SecondSecond | SecondThird |
ThirdFirst | ThirdSecond | ThirdThird |
foo | verylongwordinsidehere | bar |

See

  • Understanding nested list comprehension to get a better understanding what max_len = max(len(i) for j in data for i in j) does
  • python matrix transpose and zip to see how transposing a list of list with zip() works

If you need to keep it shorter you can use ' | '.join() to print the lists:

# do not use list comp for printing side effect - use a simple loop
for inner in data:
print( ' | '.join( (f"{word:{max_len}}" for word in inner)))

If you need to also print uneven lists, zip() won't do - you can get around that (research itertiols.zip_longest) but if you really need that, ask a new question with data for that after you tried something to do what you need it to do.

Printing list-of-lists in tabular form in Python

You could use format(), the {i:length} in string, will be replaced by the parameters, where i is an order identifier, and length is the "length" of the field.

def dvdprintsoftlist():
list_of_DVDsuppliers=[["a","m",15],["w","p",34]]
print(list_of_DVDsuppliers)
print
''' printing the available DVDstocks,supplier's details '''
print("This is your current list of stock")
print("Supplier Name\t\tSoftwear Name\t\tAmount")
print("----------------------------------------------------------------")
for [name, softname, amount] in list_of_DVDsuppliers:
print("{0:23} {1:23} {2:5}".format(name, softname, amount))
print("----------------------------------------------------------------")
print("")

dvdprintsoftlist()

Pretty printing a list in a tabular format

mylist = [ ( ('12', '47', '4', '574862', '58', '7856'), 'AGGREGATE_VALUE1'),
( ('2', '75', '757', '8233', '838', '47775272785'), 'AGGREG2'),
( ('4144', '78', '78965', '778', '78578', '2'), 'AGGREGATE_VALUE3')]

longg = dict.fromkeys((0,1,2,3,4,5,6),0)

for tu,x in mylist:
for i,el in enumerate(tu):
longg[i] = max(longg[i],len(str(el)))
longg[6] = max(longg[6],len(str(x)))

fofo = ' '.join('%'+str(longg[i])+'s' for i in xrange(0,7))
print '\n'.join(fofo % (a,b,c,d,e,f,g) for (a,b,c,d,e,f),g in mylist)

result

  12  47      4  574862     58         7856  AGGREGATE_VALUE1
2 75 757 8233 838 47775272785 AGGREG2
4144 78 78965 778 78578 2 AGGREGATE_VALUE3

Don't know if this fills your need

EDIT 1

Using string formatting with modulo operator (%) to print in a constant length, '%6s' right-justifies in a constant length of 6, and '%-6s' left-justifies in a constant length of 6.

You'll find precisions here

But there is no sense to specify a constant length to print something at the end of a string, because it's somewhat naturally-left-justified in this case.
Then :

longg = dict.fromkeys((0,1,2,3,4,5,),0)

for tu,x in mylist:
for i,el in enumerate(tu):
longg[i] = max(longg[i],len(str(el)))

fofo = ' '.join('%'+str(longg[i])+'s' for i in xrange(0,6)) + ' %s'
print '\n'.join(fofo % (a,b,c,d,e,f,g) for (a,b,c,d,e,f),g in mylist)

EDIT 2

mylist = [ ( (12, 47, 4, 574862, 58, 7856), 'AGGREGATE_VALUE1'),
( (2, 75, 757, 8233, 838, 47775272785), 'AGGREG2'),
( (4144, 78, 78965, 778, 78578, 2), 'AGGREGATE_VALUE3')]

longg = dict.fromkeys((0,1,2,3,4,5),0)

for tu,_ in mylist:
longg.update(( i, max(longg[i],len(str(el))) ) for i,el in enumerate(tu))

fofo = ' '.join('%%%ss' % longg[i] for i in xrange(0,6)) + ' %s'
print '\n'.join(fofo % (a,b,c,d,e,f,g) for (a,b,c,d,e,f),g in mylist)

EDIT 3

mylist = [ ( (12, 47, 4, 574862, 58, 7856), 'AGGREGATE_VALUE1'),
( (2, 75, 757, 8233, 838, 47775272785), 'AGGREG2'),
( (4144, 78, 78965, 778, 78578, 2), 'AGGREGATE_VALUE3')]

header = ('Price1','Price2','reference','XYD','code','resp','AGGREG values')

longg = dict(zip((0,1,2,3,4,5,6),(len(str(x)) for x in header)))

for tu,x in mylist:
longg.update(( i, max(longg[i],len(str(el))) ) for i,el in enumerate(tu))
longg[6] = max(longg[6],len(str(x)))
fofo = ' | '.join('%%-%ss' % longg[i] for i in xrange(0,7))

print '\n'.join((fofo % header,
'-|-'.join( longg[i]*'-' for i in xrange(7)),
'\n'.join(fofo % (a,b,c,d,e,f,g) for (a,b,c,d,e,f),g in mylist)))

result

Price1 | Price2 | reference | XYD    | code  | resp        | AGGREG values   
-------|--------|-----------|--------|-------|-------------|-----------------
12 | 47 | 4 | 574862 | 58 | 7856 | AGGREGATE_VALUE1
2 | 75 | 757 | 8233 | 838 | 47775272785 | AGGREG2
4144 | 78 | 78965 | 778 | 78578 | 2 | AGGREGATE_VALUE3

Note that this kind of formatting would be much easier with the string's method format() introduced in Python 2.6



Related Topics



Leave a reply



Submit