badner badner - 1 month ago 11
Python Question

list organized into columns not rows

I have a list of lists that I am trying to write to columns instead of rows. My list looks like this:

['31 32 31 8', '31 31 32 8', '31 31 31 8', '31 32 31 31']


I want it to llok like this:

31 31 31 31
32 31 31 32
31 32 31 31
8 8 8 31


I can get a nice print in rows like this:

with open("text.csv", 'w') as f:
for x in zip(contents):
f.write('\t'.join(x)+'\n')


What I would like to do is get this data in columns

Answer

You may use zip() for this. Firstly convert your list of string to list of list using str.split(), then iterate over ziped list. Below is the sample code:

>>> my_list = ['31 32 31 8', '31 31 32 8', '31 31 31 8', '31 32 31 31']
>>> my_list_list = [s.split() for s in my_list]
>>> for item in zip(*my_list_list):
...     print item
...
('31', '31', '31', '31')
('32', '31', '31', '32')
('31', '32', '31', '31')
('8', '8', '8', '31')