Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python cut list by a certain word

Tags:

python

list

I have a list like this:

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

and i am searching for a method that cut in 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 cycle but nothing done.

but i don't have idea how this is possible with python. Someone have an idea?

Thanks in advance

like image 916
Manuel Santi Avatar asked Aug 12 '26 06:08

Manuel Santi


1 Answers

I would favour a simple for loop 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]]]

There's probably a shorter solution, but I doubt it'd be a better one.

Edit: Found a shorter version with itertools.groupby (still prefer the loop though):

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]]]
like image 198
cs95 Avatar answered Aug 15 '26 06:08

cs95



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!