List all contiguous sub-arrays

后端 未结 4 436
醉酒成梦
醉酒成梦 2020-12-29 15:14

I have an array [1, 2, 3] of integer and I need to return all the possible combination of contiguous sub-arrays of this array.

[[1],[2],[3],[1,2],

4条回答
  •  情深已故
    2020-12-29 15:58

    One line solution (I don't know what means "better way" for you)

    L = [1,2,3]
    [L[i:i+j] for i in range(0,len(L)) for j in range(1,len(L)-i+1)]
    
    L=[1,2,3,4]
    [L[i:i+j] for i in range(0,len(L)) for j in range(1,len(L)-i+1)]
    

    you get,

    [[1], [1, 2], [1, 2, 3], [2], [2, 3], [3]]
    
    [[1],
     [1, 2],
     [1, 2, 3],
     [1, 2, 3, 4],
     [2],
     [2, 3],
     [2, 3, 4],
     [3],
     [3, 4],
     [4]]
    

提交回复
热议问题