每次出现元素时,将列表分为子列表,从特定子字符串开始

时间:2019-07-01 18:32:38

标签: python python-2.7 list formatting nested-lists

我有一个很大的列表,其中包含一串字符串。我需要将原始列表的元素排序到一个嵌套列表中,这取决于它们在列表中的位置。换句话说,我需要将原始列表分为多个子列表,每个子列表包含所有以'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')]

1 个答案:

答案 0 :(得分: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]