任何标准的python库在列表上提供拆分连接功能?

时间:2013-08-14 09:45:31

标签: python list join split

是否有任何标准的python库可以让你做这样的事情?

>>> [1,0,2,3,0,5,6].split([0])
>>> [[1],[2,3],[5,6]]

>>> [[1],[2,3],[5,6]].join([0])
>>> [1,0,2,3,0,5,6]

对我来说,感觉就像一个非常基本的东西,经常需要。 请注意,字符串默认支持这些方法。

2 个答案:

答案 0 :(得分:1)

不确定是否有任何内置函数可以轻松完成此操作,但您可以使用itertools:

>>> from itertools import groupby, chain, islice, cycle
>>> lis = [1,0,2,3,0,5,6]
>>> [list(g) for k, g in groupby(lis, key =lambda x: x==0) if not k]
[[1], [2, 3], [5, 6]]

>>> lis1 = [[1],[2,3],[5,6]]
>>> c = [[0]]*(len(lis1) - 1)
>>> list(chain.from_iterable(roundrobin(lis1, c)))
[1, 0, 2, 3, 0, 5, 6]
第二个中使用的

Roundrobin配方:

def roundrobin(*iterables):
    "roundrobin('ABC', 'D', 'EF') --> A D E B F C"
    # Recipe credited to George Sakkis
    pending = len(iterables)
    nexts = cycle(iter(it).next for it in iterables)
    while pending:
        try:
            for next in nexts:
                yield next()
        except StopIteration:
            pending -= 1
            nexts = cycle(islice(nexts, pending))

答案 1 :(得分:0)

不了解标准库,这里有一个对split

有点笨拙的解决方案
>>> a = [1, 0, 2, 3, 0, 5, 6]
>>> ind = [-1] + [i for i, x in enumerate(a) if x == 0] + [len(a)]
>>> [a[i + 1:j] for i, j in zip(ind, ind[1:])]
[[1], [2, 3], [5, 6]]

这是join

>>> l2 = [[1], [2, 3], [5, 6]]
>>> [i for x in l2 for i in x + [0]][:-1]
[1, 0, 2, 3, 0, 5, 6]