根据分隔符拆分列表 [英] 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']
result = [['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).
这篇关于根据分隔符拆分列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!