简体   繁体   中英

Python cut list by a certain word

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]]]

Here is 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 doesn't require specifying the delimiters, is using a lambda function as the groupby 's key function (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]]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM