开发者

how do you split a string to create nested list?

How would you split a string like

'1,55,开发者_Go百科6,89,2|7,29,44,5,8|767,822,999'

on the two delimiters ',' and '|' such that you have a list with the values like:

[[1, 55, 6, 89, 2], [7, 29, 44, 5, 8], [767, 822, 999]]


List comprehension are the most terse way to accomplish this.

>>> s = '1,55,6,89,2|7,29,44,5,8|767,822,999'
>>> [[int(x) for x in ss.split(',')] for ss in s.split('|')]
[[1, 55, 6, 89, 2], [7, 29, 44, 5, 8], [767, 822, 999]]


my_data = [x.split(',') for x in input_string.split('|')]


my_data = [map(int, line.split(',')) for line in input_string.split('|')]


import re


regx = re.compile('(\A)|(\|)|(\Z)')

def repl(mat, di = {1:'[[', 2:'],[', 3:']]'} ):
    return di[mat.lastindex]

ss = '1,55,6,89,2|7,29,44,5,8|767,822,999'

my_data = eval( regx.sub(repl,ss) )

print my_data[1]
print my_data[1][2]

result

[7, 29, 44, 5, 8]
44

I know: some will scream to not use eval()

Edit

ss = '1,55,6,89,2|7,29,44,5,8|767,822,999' 
my_data = eval( ss.replace('|','],[').join(('[[',']]')))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜