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 zip()
:
with open('data.txt','w') as f:
lis=[[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15]]
for x in zip(*lis):
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
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)
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