[英]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.我尝试使用 zip 但做不到。 Thanks in advance.
提前致谢。
Read the rows, then use zip
to read in th other way by pairing each row:读取行,然后使用
zip
通过配对每一行以其他方式读取:
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']]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.