How can I align every word from this list?

前端 未结 2 1905
遇见更好的自我
遇见更好的自我 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: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

提交回复
热议问题