How can I align every word from this list?

|▌冷眼眸甩不掉的悲伤 提交于 2021-02-17 07:11:50

问题


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.


回答1:


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  



回答2:


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



来源:https://stackoverflow.com/questions/63023871/how-can-i-align-every-word-from-this-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!