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!
You can write your own split function for lists quite easily by using yield:
An alternative way is to use
list.index
and catch the exception:Either way you can call it like this:
Result:
For parsing in Python you might also want to look at something like pyparsing.
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
result: