Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

data table in Python

I've got a 2D list in Python like this:

[['Something', 'Something else', 'Another thing'],
 ['Other things', 'More data', 'Element'],
 ['Stuff', 'data', 'etc']]

I want it to be printed out like this:

    Something    Something else Another thing
    Other things More data      Element
    Stuff        data           etc
like image 701
Dan Hlavenka Avatar asked Apr 27 '26 11:04

Dan Hlavenka


1 Answers

l = [['Something', 'Something else', 'Another thing'],
     ['Other things', 'More data', 'Element'],
     ['Stuff', 'data', 'etc']]
sub1 = [
    [s.ljust(max(len(i) for i in column)) for s in column]
    for column in zip(*l)]
for p in [" ".join(row) for row in zip(*sub1)]: print p

Here, first the list gets transformed with zip(*l): each of the sub lists gets passed as an own argument to zip(). The result is a list which combines the n-th entries of each old list, so you get [['Something', 'Other things', 'Stuff'], ['Something else', 'More data', 'data'], ...].

Then the entries whose lengths are to be matched are in the same column. In each of these columns the strings are ljust()ed to the greatest length in the group.

After that, the new list with the adjusted lengths is transformed again - in the same way as above - and the components joined with a " " in-between.

The resulting 1D list is then printed entry by entry.

like image 93
glglgl Avatar answered Apr 29 '26 00:04

glglgl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!