views:

135

answers:

2

Hi,

I'm writing a parser in Python. I've converted an input string into a list of tokens, such as:

['(', '2', '.', 'x', '.', '(', '3', '-', '1', ')', '+', '4', ')', '/', '3', '.', 'x', '^', '2']

I want to be able to split the list into multiple lists, like the str.split('+') function. But there doesn't seem to be a way to do my_list.split('+'). Any ideas?

Thanks!

+7  A: 

You can write your own split function for lists quite easily by using yield:

def split_list(l, sep):
    current = []
    for x in l:
        if x == sep:
            yield current
            current = []
        else:
            current.append(x)
    yield current

An alternative way is to use list.index and catch the exception:

def split_list(l, sep):
    i = 0
    try:
        while True:
            j = l.index(sep, i)
            yield l[i:j]
            i = j + 1
    except ValueError:
        yield l[i:]

Either way you can call it like this:

l = ['(', '2', '.', 'x', '.', '(', '3', '-', '1', ')', '+', '4', ')',
     '/', '3', '.', 'x', '^', '2']

for r in split_list(l, '+'):
    print r

Result:

['(', '2', '.', 'x', '.', '(', '3', '-', '1', ')']
['4', ')', '/', '3', '.', 'x', '^', '2']

For parsing in Python you might also want to look at something like pyparsing.

Mark Byers
[Python Lex-Yacc (PLY)](http://www.dabeaz.com/ply/) and [PyPEG](http://fdik.org/pyPEG/) are good too.
Colorado
+1  A: 

quick hack, you can first use the .join() method to join create a string out of your list, split it at '+', re-split (this creates a matrix), then use the list() method to further split each element in the matrix to individual tokens

a = ['(', '2', '.', 'x', '.', '(', '3', '-', '1', ')', '+', '4', ')', '/', '3', '.', 'x', '^', '2']

b = ''.join(a).split('+')
c = []

for el in b:
    c.append(list(el))

print(c)

result:

[['(', '2', '.', 'x', '.', '(', '3', '-', '1', ')'], ['4', ')', '/', '3', '.', 'x', '^', '2']]
momo
This probably doesn't do what he wants for `a = ['12', '+', '34']`.
Mark Byers
you're right, didn't think about that
momo