Reputation: 198
I have been given the input in string format:
"""4
101,CS101,10
101,CS102,20
102,CS102,30
102,CS101,10"""
I want to convert it to a list in a format
[["101","101","102","102"], ["CS101","CS102","CS102","CS101"], ["10","20","30","10"]]
I tried using zip but could not do it. Thanks in advance.
Upvotes: 0
Views: 47
Reputation: 4761
Try this:
s = """4
101,CS101,10
101,CS102,20
102,CS102,30
102,CS101,10"""
l = s.replace('4','').replace('\n', ',')[1:].split(',')
cols = [l[n::3] for n in range(int(len(l)/4))]
#[['101', '101', '102', '102'], ['CS101', 'CS102', 'CS102', 'CS101'],
#['10', '20', '30', '10']]
Upvotes: 0
Reputation: 54148
Read the rows, then use zip
to read in th other way by pairing each row :
v = """4
101,CS101,10
101,CS102,20
102,CS102,30
102,CS101,10"""
rows = [row.split(',') for row in v.splitlines()[1:]]
cols = list(zip(*rows))
# rows [['101', 'CS101', '10'], ['101', 'CS102', '20'], ['102', 'CS102', '30'], ['102', 'CS101', '10']]
# cols [('101', '101', '102', '102'), ('CS101', 'CS102', 'CS102', 'CS101'), ('10', '20', '30', '10')]
Upvotes: 2