Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python max length of j-th item across sublists of a list

I have a list such as:

x = [['aaa', 'bb','ccc'], ['ophkn','h','aa']]

Assume that len(x[i]) is the same for all valid values of i (0 and 1 in the above example).

Now, I need to construct a list containing the maximum length of the jth item in each sublist of x. That is, I need to know the following:

max(len(x[i][j])) over all values of i for a fixed value of j

So, in my example above, I would produce a list such as the following:

[5, 2, 3]

because

max(len('aaa'),len('ophkn')) --> 5
max(len('bb'),len('h'))      --> 2
max(len('ccc'),len('aa'))    --> 3

The reason I'm trying to find these max values is so I can print a table with filled space such as the following:

aaa    bb  ccc
ophkn  h   aa

So, if anyone has an elegant way of printing x such that it aligns in tubular format, please share!

like image 681
synaptik Avatar asked Dec 19 '22 11:12

synaptik


1 Answers

Using zip() is another way to do it:

>>> [max(len(a), len(b)) for a, b in zip(*x)]
[5, 2, 3]

As Robb pointed out in the comments, a generic and efficient way of doing this for arbitrary number of rows would be:

[max(len(b) for b in a) for a in zip(*x)]
like image 81
shaktimaan Avatar answered Jan 06 '23 21:01

shaktimaan