Python根据定界符分割列表 [英] Python splitting a list based on a delimiter word
问题描述
我有一个包含各种字符串值的列表.每当我看到WORD
时,我都想拆分列表.结果将是一个列表列表(将是原始列表的子列表),该列表仅包含WORD
的一个实例.我可以使用循环执行此操作,但是有 more pythonic 方式可以执行此操作实现这一目标?
I have a list containing various string values. I want to split the list whenever I see WORD
. The result will be a list of lists (which will be the sublists of original list) containing exactly one instance of the WORD
I can do this using a loop but is there a more pythonic way to do achieve this ?
示例= ['A', 'WORD', 'B' , 'C' , 'WORD' , 'D']
结果= [['A'], ['WORD','B','C'],['WORD','D']]
这是我尝试过的方法,但实际上并没有达到我想要的效果,因为它将WORD
放置在应包含的其他列表中:
This is what I have tried but it actually does not achieve what I want since it will put WORD
in a different list that it should be in:
def split_excel_cells(delimiter, cell_data):
result = []
temp = []
for cell in cell_data:
if cell == delimiter:
temp.append(cell)
result.append(temp)
temp = []
else:
temp.append(cell)
return result
推荐答案
我会使用生成器:
def group(seq, sep):
g = []
for el in seq:
if el == sep:
yield g
g = []
g.append(el)
yield g
ex = ['A', 'WORD', 'B' , 'C' , 'WORD' , 'D']
result = list(group(ex, 'WORD'))
print(result)
此打印
[['A'], ['WORD', 'B', 'C'], ['WORD', 'D']]
该代码接受任何可迭代的代码,并生成一个可迭代的代码(如果不需要,您可以 将其平化为列表).
The code accepts any iterable, and produces an iterable (which you don't have to flatten into a list if you don't want to).
这篇关于Python根据定界符分割列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!