5

是否有任何标准的 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]

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

4

2 回答 2

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))
于 2013-08-14T09:53:23.337 回答
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]
于 2013-08-14T10:00:41.673 回答