Splitting a list in python

前端 未结 2 1838
悲&欢浪女
悲&欢浪女 2021-01-13 01:36

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

[\'(\', \'2\', \'.\', \'x\', \'.\', \'(\', \'3\', \'-\', \'1\'

2条回答
  •  余生分开走
    2021-01-13 02:03

    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.

提交回复
热议问题