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!
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)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With