如何从展平列表创建嵌套列表?

use*_*310 4 python python-3.x

我写了一个函数来创建一个嵌套列表.

例如:

input= ['a','b','c','','d','e','f','g','','d','s','d','a','']
Run Code Online (Sandbox Code Playgroud)

我想先创建一个子列表 ''

作为回报,我想要一个嵌套列表,如:

[['a','b','c'],['d','e','f','g'],['d','s','d','a']]
Run Code Online (Sandbox Code Playgroud)

Abh*_*jit 5

尝试以下实现

>>> 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']]
Run Code Online (Sandbox Code Playgroud)

另一种可能的实现方式可能是itertools.groupby.但是你必须过滤结果以删除[''].但是虽然它可能看起来像单行,但上面的实现更直观和可读更pythonic

>>> 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']]
Run Code Online (Sandbox Code Playgroud)