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

jfouhy@paradise.net.nz jfouhy at paradise.net.nz
Fri Jun 17 14:35:24 CEST 2005


Quoting János Juhász <janos.juhasz at VELUX.com>:

> 
> Dear Guys,
> 
> 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.
> 
> I hope that, it can wrote with some nice list comprehension, but I can't
> do that :(

There is a magic trick: You can use zip(* ) to transpose a two-dimensional array.

eg:

>>> arr = [[1,2,3], [4,5,6]]
>>> zip(*arr)
[(1, 4), (2, 5), (3, 6)]
>>> zip(*zip(*arr))
[(1, 2, 3), (4, 5, 6)]

(if this is not obvious to you, I recommend spending the time to figure out how
this works)

You can use this to easily get at the columns of your array.  And once you have
the columns, you can use a list comprehension to get the lengths of the elements
and find the max.

eg:

>>> arr = [['a'*random.randint(1, 10) for i in range(5)] for j in range(10)]
>>> pprint.pprint(arr)
[['aaaaaa', 'a', 'aaaaaaaaaa', 'aaaa', 'aaaaaaaa'],
 ['aaaaaaa', 'aaaaaa', 'aaaaaaaaaa', 'aaa', 'aaa'],
 ['aa', 'aaaaaaa', 'aaaaaaaa', 'aaaaaa', 'aaaaaaa'],
 ['aaaaaaaa', 'aaaaaa', 'aaaaaaaaaa', 'aa', 'aa'],
 ['aaaaaaaaaa', 'aaaaa', 'aaaaaa', 'a', 'aaaa'],
 ['aaaaaaa', 'aaaaaaaaa', 'aaaaaa', 'aaaaa', 'aaaaaaaaaa'],
 ['aaaa', 'aaaaaaaaa', 'aaaaa', 'aaaa', 'aaaaaaaaaa'],
 ['aaaaa', 'aaa', 'aaaaaaaaa', 'aa', 'aaaaaaa'],
 ['aaaaaaaa', 'aaaaaa', 'aaaaaa', 'a', 'aaaaa'],
 ['aaaaaaaaa', 'aaaaaa', 'aaaaaa', 'aaa', 'aaaaaa']]
>>> [max([len(s) for s in l]) for l in zip(*arr)]
[10, 9, 10, 6, 10]

HTH!

-- 
John.


More information about the Tutor mailing list