开发者

How to slice list into contiguous groups of non-zero integers in Python

开发者 https://www.devze.com 2023-03-22 03:14 出处:网络
Can\'t seem开发者_如何学Python to find a clue to this online and can\'t figure it out myself so:

Can't seem开发者_如何学Python to find a clue to this online and can't figure it out myself so:

How would I go about slicing a list so that I return a list of slices of contiguous non-zero integers. ie:

data = [3, 7, 4, 0, 1, 3, 7]

and I want to produce:

slices = [[3, 7, 4], [1, 3, 7]]

I have tried various methods of iterating through the list, have been leaning towards a generator that lets me know when the contiguous groups start and stop, by testing if there is a 0 before or after, but then I am a bit stumped.


import itertools
[ list(x[1]) for x in itertools.groupby(data, lambda x: x == 0) if not x[0] ]


Look at itertools.groupby:

>>> data = [3, 7, 4, 0, 1, 3, 7, 4, 0, 5]
>>> a=[list(i[1]) for i in itertools.groupby(data, key=lambda i:i==0)]
>>> a
[[3, 7, 4], [0], [1, 3, 7, 4], [0], [5]]
>>> [i for i in a if i != [0]]
[[3, 7, 4], [1, 3, 7, 4], [5]]


def split_on_zero(data):
    start = 0
    for (i, n) in enumerate(data):
        if n == 0:
            yield data[start:i]
            start = i + 1
    yield data[start:]

>>> list(split_on_zero([3, 7, 4, 0, 1, 3, 7]))
[[3, 7, 4], [1, 3, 7]]
>>> list(split_on_zero([0, 1, 2, 0, 3, 4, 5, 0]))
[[], [1, 2], [3, 4, 5], []]


Here the very base solution you can try to use too:

data = [1, 0, 3, 7, 4, 1, 3, 7]

def get_zero_sliced(inputList):
    res = []
    prev = 0
    for i,x in enumerate(data):
        if x == 0 and i != 0:
            res.append(data[prev:i])
            prev = i + 1
        if i == len(data)-1 and prev != i:
            res.append(data[prev:])
    return res

get_zero_sliced(data)


A generator will work. Here's one, but there's probably other ways to do it. I called it x because I don't have a good name right now (good naming takes some thought, so give it some thought).

def x(iterator):
    result = []
    for i in iterator:
        if i != 0:
            result.append(i)
        elif result:
            yield result
            result = []
    if result: yield result
0

精彩评论

暂无评论...
验证码 换一张
取 消