[英]Split list into sublists at every occurrence of element starting with specific substring
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.
换句话说,我需要将原始列表分解为子列表,其中每个子列表包含所有以'ABC'开头的元素之间的所有元素,然后将它们作为嵌套列表连接在一起。
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')]
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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.