# [Tutor] max(len(item)) for cols

János Juhász janos.juhasz at VELUX.com
Mon Jun 20 09:24:10 CEST 2005

```Dear Alan,

similar :)

I have scripted a small sql e-mail reporting simplified from
# written by Mike Brown
# http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/148061

import string

def TableStr(labels, rows, delim=' | '):
columns = zip(*[labels] + rows)
# get the maximum of each column by the string length of its items
maxWidths = [max([len(str(cell)) for cell in column]) for column in
columns]
result = delim.join(
[str.ljust(str(item),width) for (item,width) in
zip(labels,maxWidths)]
)+'\n'
result +=  '='*(sum(maxWidths) + len(delim)*(len(columns)-1))+'\n'
for row in rows:
result += delim.join(
[str.ljust(str(item),width) for (item,width) in
zip(row,maxWidths)]
)+'\n'
return result

data = """\
WH,Stock,Qty
01,1001,10
01,1002,23
02,1432,4
03,This is long stockcode,100"""

table = string.split(data, '\n')
labels = string.split(table[0], ',')
rows = [string.split(row, ',') for row in table[1:]]

print ''
print TableStr(labels, rows, delim=' | ')

It makes beautiful tables from sql queries into e-mail as warning.

That I don't know is the asterisk in zip(*[labels] + rows)
I wasn't able to find in the python reference  what it means.
May you help me in that ?

Yours sincerely,
______________________________
János Juhász

"Alan G"
<alan.gauld at freenet.co
.uk>                   To
János Juhász <janos.juhasz at VELUX.com>, <tutor at python.org>
cc
2005.06.17 19:59
Subject
Re: [Tutor] max(len(item)) for cols

I have a 2D array:
>>>[['1', '2 ', '3    '], ['longer     ', 'longer    ', 'sort']]

> How can I  get what is the max(len(item)) for the columns ?
> I would like to get a list with the max_col_width values.

>>> tda = [['1', '2 ', '3    '], ['longer     ', 'longer    ',
'sort']]
>>> mcw = [[len(r) for r in c] for c in tda]
>>> mcw
[[1, 2, 5], [11, 10, 4]]
>>> mcw = [max([len(r) for r in c]) for c in tda]
>>> mcw
[5, 11]
>>> widest = max(mcw)
>>> widest
11

Is that what you mean?

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld

```