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

后端 未结 5 580
旧巷少年郎
旧巷少年郎 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: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], []]
    

提交回复
热议问题