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.
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With