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!
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)
.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
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With