How can I align every word from this list?

前端 未结 2 1861
遇见更好的自我
遇见更好的自我 2021-01-29 06:17

I have a list of lists in a file:

[ [ \'aaaaa\', \'bbb\',\'ccccccccc\' ], [ \'aaaaa\', \'bbbbbb\',\'cccccc\' ], [ \'aaa\', \'bbb\',\'ccccccccc\' ] ]
相关标签:
2条回答
  • 2021-01-29 06:35

    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  
    
    0 讨论(0)
  • 2021-01-29 06:36
    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

    0 讨论(0)
提交回复
热议问题