I have a list "localisation" which contains 3 sublists. I want to print this list to a file with each sublist in a column.
eg:
>>>print localisation
localisation = [['a', 'b', 'c'],['d', 'e', 'f'],['g', 'h', 'i']]
I want a file that looks like:
a d g
b e h
c f i
(columns can be separated by a single space, a tab etc)
At the moment I am doing it as follows:
with open("rssi.txt") as fd:
for item in localisation:
print>>fd, item
Is there a better way of doing it eg a single line that prints the whole list in at one time?
localisation = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']]
with open("rssi.txt") as f:
f.write('\n'.join(' '.join(row) for row in zip(*localisation)))
# a d g
# b e h
# c f i
>>> localisation = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']]
>>> zip(*localisation)
[('a', 'd', 'g'), ('b', 'e', 'h'), ('c', 'f', 'i')]
with open("rssi.txt", "w") as f:
for col in zip(*localisation):
f.write(' '.join(str(x) for x in col) + '\n')
If every item in your inner list is already a string you can just use ' '.join(col) + '\\n'
, to separate by tabs instead of spaces use '\\t'.join(...)
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.