4

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

例如:

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

我想在之前创建一个子列表''

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

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

3 回答 3

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']]
于 2012-11-12T07:59:12.583 回答
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']]
于 2012-11-12T09:15:46.887 回答
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

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

于 2012-11-12T08:02:12.433 回答