Python has shortened a list by a specific word

I have a list like this:

[["tab1", None], ["val1", 10], ["val2", "test"], ["val3", 20], ["tab2", None], ["val4", "test"], ["val5", 30]]

      

and I am looking for a method that slices n lists, if the word "tab" is found, the result could be this:

list1 = [["val1", 10], ["val2", "test"], ["val3", 20]]

list2 = [["val4", "test"], ["val5", 30]]

      

I try with some for a loop but nothing is done.

but I have no idea how this is possible with python. Anyone have an idea?

Thank you in advance

+3


source to share


2 answers


I would prefer a simple loop for

for this:

In [56]: new_l = []

In [57]: for i in l:
    ...:     if 'tab' in i[0]:
    ...:         new_l.append([])
    ...:     else:
    ...:         new_l[-1].append(i)
    ...:          

In [58]: new_l
Out[58]: 
[[['val1', 10], ['val2', 'test'], ['val3', 20]],
 [['val4', 'test'], ['val5', 30]]]

      

This is probably a shorter solution, but I doubt it would be better.



Edit: Found a shorter version with itertools.groupby

(still prefer loop):

In [66]: [list(v) for _, v in filter(lambda x: x[0], itertools.groupby(l, key=lambda x: 'tab' not in x[0] ))]    
Out[66]: 
[[['val1', 10], ['val2', 'test'], ['val3', 20]],
 [['val4', 'test'], ['val5', 30]]]

      

+7


source


Here's a pythonic way using itertools.groupby()

:

In [10]: from itertools import groupby

In [12]: delimiters = {'tab1', 'tab2'}

In [13]: [list(g) for k, g in groupby(lst, delimiters.intersection) if not k]
Out[13]: 
[[['val1', 10], ['val2', 'test'], ['val3', 20]],
 [['val4', 'test'], ['val5', 30]]]

      



A more general approach that does not require delimiters to be specified uses a lambda function as a key function groupby

(but with less performance):

In [14]: [list(g) for k, g in groupby(lst, lambda x: x[0].startswith('tab')) if not k]
Out[14]: 
[[['val1', 10], ['val2', 'test'], ['val3', 20]],
 [['val4', 'test'], ['val5', 30]]]

      

+5


source







All Articles