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

后端 未结 5 577
旧巷少年郎
旧巷少年郎 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: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)
    

提交回复
热议问题