Python list splitting

I am writing a parser in Python. I converted the input string to a list of tokens, for example:

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

I want to split a list into several lists, for example, into a function str.split('+'). But there is no way to do it my_list.split('+'). Any ideas?

Thank!

+5
source share
2 answers

You can easily write your own split function for lists with 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.indexand 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:]

In any case, 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 can also look at something like pyparsing .

+8
source

quick hack, .join() , , "+", ( ), list()

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

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

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

print(c)

:

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

All Articles