Reputation: 473
I have a large list that contains a bunch of strings. I need to sort the elements of the original list into a nested list, determined by their placement in the list. In other words, I need to break the original list into sublists, where each sublist contains all elements that fall between an element starting with 'ABC', and then join them together as a nested list.
So the original list is:
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’]
And I need to return:
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’]]
I have tried the following:
split_results = [l.split(',') for l in ','.join(all_results).split('ABC')]
Upvotes: 0
Views: 327
Reputation: 49920
You can work from your original list directly:
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]
Upvotes: 1