我正在用 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/