在python中拆分列表

tjv*_*jvr 5 python parsing list

我正在用Python编写解析器.我已将输入字符串转换为标记列表,例如:

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

我希望能够将列表拆分为多个列表,例如str.split('+')函数.但似乎没有办法my_list.split('+').有任何想法吗?

谢谢!

Mar*_*ers 8

您可以使用yield很容易地为列表编写自己的拆分函数:

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

另一种方法是使用list.index和捕获异常:

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:]
Run Code Online (Sandbox Code Playgroud)

无论哪种方式,你可以这样称呼它:

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

for r in split_list(l, '+'):
    print r
Run Code Online (Sandbox Code Playgroud)

结果:

['(', '2', '.', 'x', '.', '(', '3', '-', '1', ')']
['4', ')', '/', '3', '.', 'x', '^', '2']
Run Code Online (Sandbox Code Playgroud)

对于在Python中解析,您可能还需要查看类似pyparsing的内容.

  • [Python Lex-Yacc(PLY)](http://www.dabeaz.com/ply/)和[PyPEG](http://fdik.org/pyPEG/)也很好. (3认同)