Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any standard python libs providing split 'n join functionality on lists?

Are there any standard python libs that allow you to do stuff like this?

>>> [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]

To me it feels like a pretty basic things that is needed quite frequently. Note that strings support these methods by default.

like image 695
chtenb Avatar asked Nov 11 '22 23:11

chtenb


1 Answers

Not sure if any built-in functions are present to do this easily, but you can use 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 recipe used in the second one:

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))
like image 154
Ashwini Chaudhary Avatar answered Nov 14 '22 22:11

Ashwini Chaudhary