2

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?

2
  • 1
    The data is always separated every 4 elements? Commented Dec 4, 2016 at 17:11
  • @eyllanesc I guess OP is looking to split whenever Name.* appears Commented Dec 4, 2016 at 17:37

2 Answers 2

2

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)
Sign up to request clarification or add additional context in comments.

2 Comments

What does this line do? if Lsub:
@kurious: Lsub evaluates as False when it is an empty list.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.