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

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

提交回复
热议问题