I have a list that has some specific elements in it. I would like to split that list into 'sublists' or different lists based on those elements. For example:
test_list = ['a and b, 123','1','2','x','y','Foo and Bar, gibberish','123','321','June','July','August','Bonnie and Clyde, foobar','today','tomorrow','yesterday']
I would like to split into sublists if an element matches 'something and something':
new_list = [['a and b, 123', '1', '2', 'x', 'y'], ['Foo and Bar, gibberish', '123', '321', 'June', 'July', 'August'], ['Bonnie and Clyde, foobar', 'today', 'tomorrow', 'yesterday']]
So far I can accomplish this if there is a fixed amount of items after the specific element. For example:
import re
element_regex = re.compile(r'[A-Z a-z]+ and [A-Z a-z]+')
new_list = [test_list[i:(i+4)] for i, x in enumerate(test_list) if element_regex.match(x)]
Which is almost there, but there's not always exactly three elements following the specific element of interest. Is there a better way than just looping over every single item?