4

I wrote a function to create a nested list.

For example:

input= ['a','b','c','','d','e','f','g','','d','s','d','a','']

I want to create a sublist before ''

As a return I want a nested list like:

[['a','b','c'],['d','e','f','g'],['d','s','d','a']]
1
  • 3
    Welcome to Stack Overflow! We encourage you to research your questions. If you've tried something already, please add it to the question - if not, research and attempt your question first, and then come back. Commented Nov 12, 2012 at 7:57

3 Answers 3

5

Try the following implementation

>>> def foo(inlist, delim = ''):
    start = 0
    try:
        while True:
            stop = inlist.index(delim, start)
            yield inlist[start:stop]
            start = stop + 1
    except ValueError:
            # if '' may not be the end delimiter 
            if start < len(inlist):
                yield inlist[start:]
        return


>>> list(foo(inlist))
[['a', 'b', 'c'], ['d', 'e', 'f', 'g'], ['d', 's', 'd', 'a']]

Another possible implementation could be by itertools.groupby. But then you have to filter the result to remove the ['']. But though it might look to be one-liner yet the above implementation is more pythonic as its intuitive and readable

>>> from itertools import ifilter, groupby
>>> list(ifilter(lambda e: '' not in e,
             (list(v) for k,v in groupby(inlist, key = lambda e:e == ''))))
[['a', 'b', 'c'], ['d', 'e', 'f', 'g'], ['d', 's', 'd', 'a']]
Sign up to request clarification or add additional context in comments.

2 Comments

This only returns the correct list if the input ends with ''. eg ['a', '', 'b'] returns [['a']] instead of [['a'], ['b']]
@Tim: As per the problem statement I want to create a sublist before ''
4

I'd use itertools.groupby:

l = ['a','b','c','','d','e','f','g','','d','s','d','a','']
from itertools import groupby
[list(g) for k, g in groupby(l, bool) if k]

gives

[['a', 'b', 'c'], ['d', 'e', 'f', 'g'], ['d', 's', 'd', 'a']]

Comments

3
def nester(nput):
   out = [[]]
      for n in nput:
         if n == '':
            out.append([])
         else:
            out[-1].append(n)
    if out[-1] == []:
       out = out[:-1]
    return out

edited to add check for empty list at end

2 Comments

but it return [['a', 'b', 'c'], ['d', 'e', 'f', 'g'], ['d', 's', 'd', 'a'], []] in the shell, how to eliminate the [] at the end?
Add an if not out[-1]: out.pop() before the return

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.