Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

python:split a list of strings into multiple lists before a certain value

I have a list as follows,

my_list = ['France, the weather is nice', 'the house is beautiful', 'we have a fresh start here','France, the dinner is amazing', 'the lady is lovely', 'France, the house is beautiful','the location is fascinating']

I want to split the list into multiple list every time the word ‘France,’ is in the string, so the output should be,

desired_list = [['France, the weather is nice', 'the house is beautiful', 'we have a fresh start here'],['France, the dinner is amazing', 'the lady is lovely'],['France, the house is beautiful','the location is fascinating']]

I have tried the following, but would like to keep the sentence that has ‘France,’ too.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

new_list =[list(y) for x, y in itertools.groupby(my_list, lambda z: z.startswith('France,)) if not x]

another answer

in addition to the answer given by Titouan L, I also found the answer using more_itertools

import more_itertools as miter
print(list(miter.split_before(my_list, lambda x: x.startswith("France,"))))

>Solution :

I’ve come up with a solution with nested loops, as I’m not very experienced with list comprehension and lambda expression.

my_list = ['France, the weather is nice', 'the house is beautiful', 'we have a fresh start here', 'France, the dinner is amazing',
           'the lady is lovely', 'France, the house is beautiful', 'the location is fascinating']

new_list = []
sub_list = []
for i in my_list:
    if i.startswith('France,'):
        if sub_list != []:
            new_list.append(sub_list)
            sub_list=[]

    sub_list.append(i)
new_list.append(sub_list)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading