Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split list of strings into list of sublists based on a string [duplicate]

This problem is most easily illustrated in pseudo-code. I have a list like this:

linelist = ["a", "b", "", "c", "d", "e", "", "a"]

I would like to get it in the format:

questionchunks = [["a", "b"], ["c", "d", "e"], ["a"]]

My first attempt is this:

questionchunks = []
qlist = []

for line in linelist:

    if (line != "" and len(qlist) != 0 ):
        questionchunks.append(qlist)
        qlist = []
    else: 
        qlist.append(line)

My output is a little messed up though. I'd be grateful for any pointers I can get.

like image 448
James Avatar asked Jan 20 '15 16:01

James


2 Answers

You are almost near your goal, this is the minimal edit required

linelist = ["a", "b", "", "c", "d", "e", "", "a"]
questionchunks = []
qlist = []
linelist.append('') # append an empty str at the end to avoid the other condn
for line in linelist:

    if (line != "" ):
        questionchunks.append(line)      # add the element to each of your chunk   
    else: 
        qlist.append(questionchunks)   # append chunk
        questionchunks = []       # reset chunk

print qlist
like image 116
Bhargav Rao Avatar answered Nov 06 '22 00:11

Bhargav Rao


This can be easily done using itertools.groupby:

>>> from itertools import groupby
>>> linelist = ["a", "b", "", "c", "d", "e", "", "a"]
>>> split_at = ""
>>> [list(g) for k, g in groupby(linelist, lambda x: x != split_at) if k]
[['a', 'b'], ['c', 'd', 'e'], ['a']]
like image 37
Ashwini Chaudhary Avatar answered Nov 05 '22 22:11

Ashwini Chaudhary