squidvision squidvision - 11 days ago 7
Python Question

Create sublists by splitting list at a value

I have a really long list. Below is an excerpt from it.

['1', '15943882', '63', '1', '-9', '-9', '-9', '-27', '1', '145',
'1', '233', '-9', '50', '20', '1', '0', '1', '2', '2', '3',
'1981', '0', '0', '0', '0', '0', '1', '10.5', '6', '13', '150',
'60', '190', '90', '145', '85', '0', '0', '2.3', '3', '-9', '-9',
'0', '-9', '-9', '-9', '-9', '-9', '-9', '6', '-9', '-9', '-9',
'2', '16', '1981', '0', '1', '1', '1', '-9', '1', '-9', '1',
'-9', '1', '1', '1', '1', '1', '1', '1', '-9', '-9', '0', '-9',
'-9', '-9', '-9', '-9', '-9', '-9', '-9', '-9', '0', '0', '0',
'0', 'name', '2', '15964847', '67', '1', '-9', '-9', '-9', '-27',
'4', '160', '1', '286', '-9', '40', '40', '0', '0', '1', '2',
'3', '5', '1981', '0', '1', '0', '0', '0', '1', '9.5', '6',
'13', '108', '64', '160', '90', '160', '90', '1', '0', '1.5',
'2', '-9', '-9', '3', '-9', '-9', '-9', '-9', '-9', '-9', '3',
'-9', '-9', '-9', '2', '5', '1981', '2', '1', '2', '2', '-9',
'2', '-9', '1', '-9', '1', '1', '1', '1', '1', '1', '1', '-9',
'-9', '0', '-9', '-9', '-9', '-9', '-9', '-9', '-9', '-9', '-9',
'0', '0', '0', '0', 'name']


How would I create 2 lists that split at value
'name'
? The index at the value
'name'
isn't always the same through the entire list, fyi.

Answer

To split the list on multiple name elements you can use itertools.groupby() from the standard modules:

>>> import itertools as it
>>> data = ['1', '15943882', '63', '1', '-9', '-9', '-9', '-27', '1', '145', '1', ...]
>>> [list(g) for k, g in it.groupby(data, lambda x: x=='name') if not k]
[['1', '15943882', '63', '1', '-9', '-9', '-9', '-27', '1', '145', ...
 ['2', '15964847', '67', '1', '-9', '-9', '-9', '-27', '4', '160', ...