Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting a list in python

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!

like image 812
tjvr Avatar asked Jun 06 '10 11:06

tjvr


People also ask

How do you split items in a list in Python?

To split the elements of a list in Python: Use a list comprehension to iterate over the list. On each iteration, call the split() method to split each string. Return the part of each string you want to keep.

How do you split a list into delimiter in Python?

Use split() method to split by delimiter. If the argument is omitted, it will be split by whitespace, such as spaces, newlines \n , and tabs \t . Consecutive whitespace is processed together. A list of the words is returned.

How do you split a list into N parts in Python?

array_split() to split a list into n parts. Call numpy. array_split(list, n) to return a list of n NumPy arrays each containing approximately the same number of elements from list . Use the for-loop syntax for array in list to iterate over each array in list .


1 Answers

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.

like image 72
Mark Byers Avatar answered Oct 06 '22 09:10

Mark Byers