在python中拆分列表 [英] Splitting a list in python
问题描述
我正在用Python编写解析器.我已经将输入字符串转换为令牌列表,例如:
I'm writing a parser in Python. I've converted an input string into a list of tokens, such as:
['(', '2', '.', 'x', '.', '(', '3', '-', '1', ')', '+', '4', ')', '/', '3', '.', 'x', '^', '2']
我希望能够将列表分成多个列表,例如str.split('+')
函数.但是似乎没有一种方法可以执行my_list.split('+')
.有什么想法吗?
I want to be able to split the list into multiple lists, like the str.split('+')
function. But there doesn't seem to be a way to do my_list.split('+')
. Any ideas?
谢谢!
推荐答案
您可以使用yield很容易地为列表编写自己的拆分函数:
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
另一种方法是使用list.index
并捕获异常:
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
结果:
['(', '2', '.', 'x', '.', '(', '3', '-', '1', ')']
['4', ')', '/', '3', '.', 'x', '^', '2']
对于使用Python进行解析,您可能还需要查看类似 pyparsing .
For parsing in Python you might also want to look at something like pyparsing.
这篇关于在python中拆分列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!