Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write a list to columns

Tags:

python

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?

like image 437
user1551817 Avatar asked Dec 07 '22 12:12

user1551817


2 Answers

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
like image 102
Ashwini Chaudhary Avatar answered Dec 18 '22 06:12

Ashwini Chaudhary


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)
like image 39
ninjagecko Avatar answered Dec 18 '22 04:12

ninjagecko