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.
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
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']]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With