InsideDarkWeb.com

How can I align every word from this list?

I have a list of lists in a file:

[ [ 'aaaaa', 'bbb','ccccccccc' ], [ 'aaaaa', 'bbbbbb','cccccc' ], [ 'aaa', 'bbb','ccccccccc' ] ]
aaaaa bbb ccccccccc
aaaaa bbbbbb cccccc
aaa bbb ccccccccc

I use it for some analysis but because of the lengths of the words, it is hard to read, I want to format it to look something like this:

aaaaa  bbb     ccccccccc
aaaaa  bbbbbb  cccccc
aaa    bbb     ccccccccc

Maybe with some generous spaces between columns.

I guess I can use .format function but I tried and I found no solution.

I can only use Python 2.7.

Stack Overflow Asked on November 15, 2021

2 Answers

2 Answers

my_list = [ [ 'aaaaa', 'bbb','ccccccccc' ], [ 'aaaaa', 'bbbbbb','cccccc' ], [ 'aaa', 'bbb','ccccccccc' ] ]

# max_lengths = [max(len(y) for y in x) for x in zip(*my_list)]
# Can do above and get max lengths for each a, b, c etc but let us just get one global max for a neater solution

max_length = max(max(inner_list) for inner_list in my_list)

with open(target, "w") as writer:
   for inner_list in my_list:
       l_justed = [x.ljust(max_length) for x in inner_list)
       writer.writeline("    ".join(l_justed))

ljust adds spaces at the end to make the string length as specified value

Answered by vestronge on November 15, 2021

Tested with Python2.7:

lst = [ [ 'aaaaa', 'bbb','ccccccccc' ], [ 'aaaaa', 'bbbbbb','cccccc' ], [ 'aaa', 'bbb','ccccccccc' ] ]

widths = [max(len(j) for j in i) for i in zip(*lst)]
s = ''.join('{{:<{}}}'.format(w+2) for w in widths)

for v in lst:
    print(s.format(*v))

Prints each column aligned to max width of string inside this column + 2 extra characters:

aaaaa  bbb     ccccccccc  
aaaaa  bbbbbb  cccccc     
aaa    bbb     ccccccccc  

Answered by Andrej Kesely on November 15, 2021

Add your own answers!

Related Questions

How to revert back to python 2.7?

1  Asked on February 14, 2021 by nikhil-shrivastava

         

Using same name for attribute and getter

1  Asked on February 13, 2021 by janpeterka

     

What is the purpose to use className beside functionName using colon(:)

1  Asked on February 13, 2021 by mahedi-hasan-durjoy

 

Python: access a variable in a module from another file

2  Asked on February 13, 2021 by yeroduk

 

How to get elements of a sublist in Java

5  Asked on February 13, 2021 by alvira

     

`SyntaxError` in if-else one-liner

2  Asked on February 13, 2021 by evgeniy-golovin

         

NiFi Consume kafka sasl_plaintext issue

1  Asked on February 13, 2021 by varun_rathinam

       

Clock divider in vhdl from 100MHz to 1Hz code

2  Asked on February 13, 2021 by mariaaaa

     

Inconsistent Paging in ASP.NET CORE

0  Asked on February 13, 2021 by addsw

       

Nuxt.js: can’t generate routes

3  Asked on February 12, 2021 by drake035

     

Ask a Question

Get help from others!

© 2021 InsideDarkWeb.com. All rights reserved.