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
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]]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With