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

后端 未结 5 561
旧巷少年郎
旧巷少年郎 2020-12-31 20:50

Can\'t seem 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

相关标签:
5条回答
  • 2020-12-31 21:16

    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 讨论(0)
  • 2020-12-31 21:22

    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)
    
    0 讨论(0)
  • 2020-12-31 21:24

    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]]
    
    0 讨论(0)
  • 2020-12-31 21:27
    import itertools
    [ list(x[1]) for x in itertools.groupby(data, lambda x: x == 0) if not x[0] ]
    
    0 讨论(0)
  • 2020-12-31 21:39
    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], []]
    
    0 讨论(0)
提交回复
热议问题