根据定界符分割列表 [英] Splitting a list based on a delimiter word

查看:49
本文介绍了根据定界符分割列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含各种字符串值的列表.每当我看到 WORD 时,我都希望拆分列表.结果将是一个列表列表(将是原始列表的子列表),该列表仅包含 WORD 的一个实例.我可以使用循环来执行此操作,但是有更多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 ?

Example = ['A','WORD','B','C','WORD','D']

Example = ['A', 'WORD', 'B' , 'C' , 'WORD' , 'D']

result = [['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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆