python - 在 python 中拆分列表

标签 python list parsing

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

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

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

谢谢!

最佳答案

您可以使用 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 的内容.

关于python - 在 python 中拆分列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2983959/

相关文章:

python - heapq.heapify 不适用于子类列表

python - Paypal 自适应支付 - 预批准请求导致 "Invalid request"错误

Python将数字列表与其他数字列表相加

objective-c - 如何通过在 Objective-C 中删除路径中的 2 个文件夹来解析 NSString

python - 如何从sql查询中提取表名和列名?

python - 从不同的 .py 文件调用函数时找不到 Errno 2 文件

python - 为什么 "else"子句的目的是在 "for"或 "while"循环之后?

python - 如何从 python 列表中的前一个值中减去该值?

python - 如何检查python列表中是否存在任何值

c# - 将6位数字解析为6个int数组