将列表拆分为值的子列表并保留该值

时间:2014-02-28 17:29:30

标签: python list split list-comprehension

我正在尝试在值上拆分列表,并保留在创建的子列表中拆分的值。我发现this solution并尝试改变它,我的时间很短。

import itertools


def isplit(iterable,splitters):
    return [list(g) for k,g in itertools.groupby(iterable,lambda x:x in splitters) if not k]

foo = [(0, 1), (1, 2), (2, 3), (0, 1),
 (2, 3), (1, 2), (1, 2), (0, 1), (2, 3),
 (1, 2), (2, 3), (0, 1), (2, 3), (0, 1),
 (1, 2), (2, 3), (1, 2), (0, 1)]

for k,g in itertools.groupby(foo,lambda x:x[0] in (0,)):
    if not k:
        print k,list(g)

上面的代码返回

[(1, 2), (2, 3)]
[(2, 3), (1, 2), (1, 2)]
[(2, 3), (1, 2), (2, 3)]
[(2, 3)]
[(1, 2), (2, 3), (1, 2)]

我希望它返回:

[(0,1),(1, 2), (2, 3)]
[(0,1),(2, 3), (1, 2), (1, 2)]
[(0,1),(2, 3), (1, 2), (2, 3)]
[(0,1),(2, 3)]
[(0,1),(1, 2), (2, 3), (1, 2)]

我该怎么做?

1 个答案:

答案 0 :(得分:3)

存储拆分组:

>>> import itertools
>>> foo = [(0, 1), (1, 2), (2, 3), (0, 1), (2, 3), (1, 2), (1, 2), (0, 1), (2, 3), (1, 2), (2, 3), (0, 1), (2, 3), (0, 1), (1, 2), (2, 3), (1, 2), (0, 1)]
>>> splitpoint = []
>>> for k,g in itertools.groupby(foo,lambda x:x[0] in (0,)):
...     if k:
...         splitpoint = list(g)
...     else:
...         print splitpoint + list(g)
... 
[(0, 1), (1, 2), (2, 3)]
[(0, 1), (2, 3), (1, 2), (1, 2)]
[(0, 1), (2, 3), (1, 2), (2, 3)]
[(0, 1), (2, 3)]
[(0, 1), (1, 2), (2, 3), (1, 2)]

或创建自己的生成器:

def group_splitter(it, key=None):
    if key is None:
        key = lambda x: x
    group = []
    for item in iter(it):
        if key(item) and group:
            yield group
            group = []
        group.append(item)
    if group:
        yield group

这也产生了最后的(0, 1)元组:

>>> def group_splitter(it, key=None):
...     if key is None:
...         key = lambda x: x
...     group = []
...     for item in iter(it):
...         if key(item) and group:
...             yield group
...             group = []
...         group.append(item)
...     if group:
...         yield group
... 
>>> for g in group_splitter(foo, lambda x: x[0] == 0):
...     print g
... 
[(0, 1), (1, 2), (2, 3)]
[(0, 1), (2, 3), (1, 2), (1, 2)]
[(0, 1), (2, 3), (1, 2), (2, 3)]
[(0, 1), (2, 3)]
[(0, 1), (1, 2), (2, 3), (1, 2)]
[(0, 1)]