简体   繁体   中英

Struggling with string to list conversion

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.

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')]

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']]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM