How to create a nested list from a smoothing list?

I wrote a function to create a nested list.

For instance:

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']] 
+4
source share
3 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 might be itertools.groupby . But then you have to filter the result to remove ['']. But although it may look one-line, the above implementation is more pythonic, because 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']] 
+5
source

I would 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']] 
+4
source
 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 the end

+3
source

Source: https://habr.com/ru/post/1445453/


All Articles