0
votes

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, 29, 44, 5, 8], [767, 822, 999]]
4

4 Answers

6
votes

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]]
0
votes
my_data = [x.split(',') for x in input_string.split('|')]
0
votes
my_data = [map(int, line.split(',')) for line in input_string.split('|')]
-3
votes
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(('[[',']]')))