Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

writing list of list into a COLUMNED .txt file via python

Tags:

python

list

I have a list that looks like

[["a","b","c","d"],["e","f","g","h"],["i","j","k","l"]]

How can I convert this list of list into a text file that looks like

a  b  c  d
e  f  g  h
i  j  k  l

It seemed straightforward but none of the solution on the web seemed concise and elucidating enough for dummies like me to understand.

Thank you!

like image 700
trenta coollime Avatar asked Feb 22 '18 08:02

trenta coollime


2 Answers

Praise the power of comprehensions here:

lst = [["a","b","c","d"],["e","f","g","h"],["i","j","k","l"]]

out = "\n".join([" ".join(sublist) for sublist in lst])
print(out)

This yields

a b c d
e f g h
i j k l

Or, longer, maybe more understandable:

for sublist in lst:
    line = " ".join(sublist)
    print(line)


If your elements have different lengths, you could leverage .format():
lst = [["a","b","cde","d"],["e","f","g","h"],["i","j","k","l"]]

out = "\n".join(["".join("{:>5}".format(item) for item in sublst) for sublst in lst])
print(out)

Which would yield

a    b  cde    d
e    f    g    h
i    j    k    l
like image 173
Jan Avatar answered Sep 25 '22 13:09

Jan


Posting just to highlight the steps you need to take

l = [['a','b','c','d'], ['e', 'f', 'g', 'h'], ['i', 'j', 'k', 'l']]
with open('my_file.txt', 'w') as f:
    for sub_list in l:
        for elem in sub_list:
            f.write(elem + ' ')
        f.write('\n')
like image 21
George Dragan Avatar answered Sep 23 '22 13:09

George Dragan