How Do You Split A String To Create Nested List?
How would you split a string like '1,55,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, 2
Solution 1:
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]]
Solution 2:
my_data = [x.split(',') for x in input_string.split('|')]
Solution 3:
my_data = [map(int, line.split(',')) for line in input_string.split('|')]
Solution 4:
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(('[[',']]')))
Post a Comment for "How Do You Split A String To Create Nested List?"