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

时间:2012-11-12 07:52:16

标签: python python-3.x

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

例如:

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

我想在''

之前创建一个子列表

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

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

3 个答案:

答案 0 :(得分: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']]

另一种可能的实施可能是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']]

答案 1 :(得分:4)

我使用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]

给出

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

答案 2 :(得分: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

编辑以在末尾添加空列表检查