在每次出现以特定子字符串开头的元素时将列表拆分为子列表

Split list into sublists at every occurrence of element starting with specific substring

提问人:cjg123 提问时间:7/2/2019 最后编辑:cjg123 更新时间:7/2/2019 访问量:271

问:

我有一个包含一堆字符串的大列表。我需要将原始列表的元素排序到嵌套列表中,由它们在列表中的位置确定。换句话说,我需要将原始列表分解为子列表,其中每个子列表包含介于以“ABC”开头的元素之间的所有元素,然后将它们连接在一起作为嵌套列表。

所以原来的列表是:

all_results = ['ABCAccount', 'def = 0', 'gg = 0', 'kec = 0', 'tend = 1234567890', 'ert = abc', 'sed = target', 'id = sadfefsd3g3g24b24b', 'ABCAccount', 'def = 0', 'gg = 0', 'kec = 0', 'tend = NA', 'ert = abc', 'sed = source', 'id = sadfefsd3g3g24b24b', 'ABCAdditional', 'addkey = weds', 'addvalue = false', 'ert = abc', 'sed = target', 'id = sadfefsd3g3g24b24b', 'time_zone = EDT’]

我需要返回:

split_results = [['ABCAccount','def = 0', 'gg = 0', 'kec = 0', 'tend = 1234567890', 'ert = abc', 'sed = target', 'id = sadfefsd3g3g24b24b'],['ABCAccount', 'def = 0', 'gg = 0', 'kec = 0', 'tend = NA', 'ert = abc', 'sed = source', 'id = sadfefsd3g3g24b24b'],['ABCAdditional', 'addkey = weds', 'addvalue = false', 'ert = abc', 'sed = target', 'id = sadfefsd3g3g24b24b', 'time_zone = EDT’]]

我尝试了以下方法:

split_results = [l.split(',') for l in ','.join(all_results).split('ABC')]
python python-2.7 列表 格式嵌 套列表

评论

0赞 Scott Hunter 7/2/2019
您经历了什么过程来生成样本输出?
0赞 cjg123 7/2/2019
认为您指的是输出是嵌套列表,这也很好
1赞 Kenny Ostrom 7/2/2019
看起来你想要一个字典的字典

答:

1赞 Scott Hunter 7/2/2019 #1

您可以直接从原始列表中工作:

def make_split( lst ):
    if len(lst) == 0:
        return []
    r0 = []
    r1 = []
    for s in lst:
        if s.startswith("ABC"):
            if r1:
                r0.append(r1)
                r1 = []
        r1.append(s)
    return r0 + [r1]