Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create nested list from flatten list?

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']]
like image 592
user1817310 Avatar asked Dec 15 '22 17:12

user1817310


2 Answers

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']]
like image 190
Abhijit Avatar answered Dec 29 '22 00:12

Abhijit


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']]
like image 21
ecatmur Avatar answered Dec 28 '22 23:12

ecatmur