在python中拆分列表

时间:2010-06-06 11:05:57

标签: python list parsing

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

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

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

谢谢!

2 个答案:

答案 0 :(得分:8)

您可以使用yield:

轻松地为列表编写自己的拆分函数
def split_list(l, sep):
    current = []
    for x in l:
        if x == sep:
            yield current
            current = []
        else:
            current.append(x)
    yield current

另一种方法是使用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:]

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

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

for r in split_list(l, '+'):
    print r

结果:

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

对于Python中的解析,您可能还希望查看类似pyparsing的内容。

答案 1 :(得分:1)

快速入侵,您可以先使用.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']]