Max K.
Max K.

Reputation: 23

Split a list into sublists based on certain string

I am pretty new to python, so my question is:

I have a list like this:

L = ['Name1', 'String1', 'String2', 'String3', 'Name2', 'String4', 'String5', 'String6', ...]

I would like to convert it into a new list in which all the strings after a certain 'name' are in a sub-list with the name like:

L2 = [['Name1', 'String1', 'String2', 'String3'],['Name2', 'String4', 'String5', 'String6'],[...]]

Whats the best way to do that?

Upvotes: 2

Views: 2127

Answers (2)

elethan
elethan

Reputation: 16993

Perhaps not the most Pythonic, but:

import re

L = ['Name1', 'String1', 'String2', 'String3', 'Name2', 'String4', 'String5', 'String6']

l_temp = re.split(r'(Name\d+)', ' '.join(L))

new_L = [[item] + l_temp[i+1].strip().split(' ') 
        for i, item in enumerate(l_temp) if item.startswith('Name')]

print new_L

"Flat is better than nested", but "simple is better than complex" and "readability counts", so...

Upvotes: 0

Marvo
Marvo

Reputation: 520

Let's assume that there is a function isname() that tells us whether an element of list L is a name:

Lsub = []
L2 = []
for e in L:
    if isname(e):
        if Lsub: 
            L2.append(Lsub)
        Lsub = [e]
    else:
        Lsub.append(e)
L2.append(Lsub)

Upvotes: 2

Related Questions