![](/img/trans.png)
[英]How can i use split function in python to split parts of text and save them to a different file?
[英]How can I split a List (in python) in different parts (after a certain element)?
我有以下问题。 我有一个包含元素的列表。 例如:
L = ['@@', ' n', ' .', ' ', '-\\', '@@', '+A', '+u', '@@', '+g', '+r', '+u']
现在,我想在每个“ @@”之后拆分列表,得到以下内容:
L1 = ['@@', ' n', ' .', ' ', '-\\']
L2 = ['@@', '+A', '+u']
L3 = ['@@', '+g', '+r', '+u']
我尝试了很多,但是我不知道该怎么做。
您可以使用生成器函数:
def split_by(iterable, split_by):
group = []
for elem in iterable:
if elem == split_by:
if group:
yield group
group = []
group.append(elem)
if group:
yield group
然后将其用作:
groups = list(split_by(L, '@@))
或使用循环:
for group in split_by(L, '@@'):
print group
演示:
>>> def split_by(iterable, split_by):
... group = []
... for elem in iterable:
... if elem == split_by:
... if group:
... yield group
... group = []
... group.append(elem)
... if group:
... yield group
...
>>> L = ['@@', ' n', ' .', ' ', '-\\', '@@', '+A', '+u', '@@', '+g', '+r', '+u']
>>> for group in split_by(L, '@@'):
... print group
...
['@@', ' n', ' .', ' ', '-\\']
['@@', '+A', '+u']
['@@', '+g', '+r', '+u']
您可以定义一个函数来执行此操作吗? 例如,
def split_list(list, delimiter):
out_list = []
for element in list:
if element == delimiter:
out_list.append([element])
else:
out_list[-1] = out_list[-1].append(element)
return out_list
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.