-1

Is there an easy way to split the list l below into 3 list. I want to cut the list when the sequence starts over. So every list should start with 1.

l= [1, 2, 3, 4, 5, 1, 2, 3, 4, 1, 2, 3, 4]
l1 = [1, 2, 3,4, 5]
l2=[1,2,3,4]
l3=[1,2,3,4]

My original thought was to look at the lead value and implement a condition inside a for loop that would cut the list when x.lead < x. But how do I use lead and lag when using lists in python?

Henri
  • 1,077
  • 10
  • 24

3 Answers3

3

NumPy solution

import numpy as np
l = [1, 2, 3, 4, 5, 1, 2, 3, 4, 1, 2, 3, 4]
parts = [list(i) for i in np.split(l,np.flatnonzero(np.diff(l)-1)+1)]
print(parts)

output

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

Explanation: I first find differences between adjacent elements using numpy.diff, then subtract 1 to be able to use numpy.flatnonzero to find where difference is other than 1, add 1 (note that numpy.diff output length is input length minus 1) to get indices for use in numpy.split, eventually convert it to list, as otherwise you would end with numpy.arrays

Daweo
  • 31,313
  • 3
  • 12
  • 25
1

What about this:

l = [1, 2, 3, 4, 5, 1, 2, 3, 4, 1, 2, 3, 4]

one_indices = [i for i, e in enumerate(l) if e == 1]

slices = []
for count, item in enumerate(one_indices):
    if count == len(one_indices) - 1:
        slices.append((item, None))
    else:
        slices.append((item, one_indices[count + 1]))

sequences = [l[x[0] : x[1]] for x in slices]
print(sequences)

Out: [[1, 2, 3, 4, 5], [1, 2, 3, 4], [1, 2, 3, 4]]

osint_alex
  • 952
  • 3
  • 16
1

Another way without numpy,

l= [1, 2, 3, 4, 5, 1, 2, 3, 4, 1, 2, 3, 4]
start = 0
newlist = []
for i,v in enumerate(l):
    if i!=0 and v==1: 
        newlist.append(l[start:i])
        start = i
newlist.append(l[start:i+1])
print(newlist)

Working Demo: https://rextester.com/RYCV85570

A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103