Write a list to columns
Question:
I have a Python list of data:
[1,2,3,4,5]
I want to read this data into a file as a column in the following way:
1
2
3
4
5
and then I want my next list ([6,7,8,9,10])
to be added to it (with a tab):
1 6
2 7
3 8
4 9
5 10
and so on.
Could anyone help me with how I can do this please?
Answers:
Use the built-in function zip()
:
with open('data.txt', 'w') as f:
lst = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15]]
for x in zip(*lst):
f.write("{0}t{1}t{2}n".format(*x))
output:
1 6 11
2 7 12
3 8 13
4 9 14
5 10 15
If you have a list of all these lists, like
data = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]
you can transpose it with zip(*data)
to get
[[1, 6], [2, 7], [3, 8], [4, 9], [5, 10]]
and then write these out with something like
with open('filename', 'w') as f:
for row in zip(*data):
f.write('t'.join(row)+'n')
col1,col2 = [1,2,3,4,5],[6,7,8,9,10]
>>> output = 'n'.join('t'.join(map(str,row)) for row in zip(col1,col2))
>>> print(output)
1 6
2 7
3 8
4 9
5 10
To write to a file:
with open('output.txt', 'w') as f:
f.write(output)
>>> from itertools import izip
>>> with open('in.txt') as f:
... input = [s.strip() for s in f.readlines()]
...
>>> input
['1', '2', '3', '4', '5']
>>> combine = ['6','7','8','9','10']
>>> with open('out.txt','w') as f:
... for x in izip(input,combine):
... f.write("{0}t{1}n".format(x[0],x[1]))
...
>>> quit()
burhan@sandbox:~$ cat out.txt
1 6
2 7
3 8
4 9
5 10
I have a Python list of data:
[1,2,3,4,5]
I want to read this data into a file as a column in the following way:
1
2
3
4
5
and then I want my next list ([6,7,8,9,10])
to be added to it (with a tab):
1 6
2 7
3 8
4 9
5 10
and so on.
Could anyone help me with how I can do this please?
Use the built-in function zip()
:
with open('data.txt', 'w') as f:
lst = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15]]
for x in zip(*lst):
f.write("{0}t{1}t{2}n".format(*x))
output:
1 6 11
2 7 12
3 8 13
4 9 14
5 10 15
If you have a list of all these lists, like
data = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]
you can transpose it with zip(*data)
to get
[[1, 6], [2, 7], [3, 8], [4, 9], [5, 10]]
and then write these out with something like
with open('filename', 'w') as f:
for row in zip(*data):
f.write('t'.join(row)+'n')
col1,col2 = [1,2,3,4,5],[6,7,8,9,10]
>>> output = 'n'.join('t'.join(map(str,row)) for row in zip(col1,col2))
>>> print(output)
1 6
2 7
3 8
4 9
5 10
To write to a file:
with open('output.txt', 'w') as f:
f.write(output)
>>> from itertools import izip
>>> with open('in.txt') as f:
... input = [s.strip() for s in f.readlines()]
...
>>> input
['1', '2', '3', '4', '5']
>>> combine = ['6','7','8','9','10']
>>> with open('out.txt','w') as f:
... for x in izip(input,combine):
... f.write("{0}t{1}n".format(x[0],x[1]))
...
>>> quit()
burhan@sandbox:~$ cat out.txt
1 6
2 7
3 8
4 9
5 10