Divide the list into ascending sequences using itertools

I have a list with mixed sequences like

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

I want to know how I can use itertools to split a list into ascending sequences, shortening the list while decreasing the points. For example, the above will output

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

this was obtained by noting that the sequence decreases by 2, so we cut the first bit there, and reduce the other with one cut there.

Another example is the sequence

[3,2,1]

the conclusion should be

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

If this sequence increases, we return the same sequence. for instance

[1,2,3]

returns the same result. iee

[[1, 2, 3]]

For a repeating list, e.g.

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

the conclusion should be

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

What I did for this is to define the following function

def splitter (L):
    result = []
    tmp = 0
    initialPoint=0
    for i in range(len(L)):
       if (L[i] < tmp):
           tmpp = L[initialPoint:i]
           result.append(tmpp)
           initialPoint=i
       tmp = L[i]
    result.append(L[initialPoint:])
    return result

100%, itertools, . itertools, ?

+4
3

numpy numpy.split, , ; , , numpy.diff , , numpy.where , :

import numpy as np
lst = [ 1, 2,2,2, 1, 2, 3, 3, 1,1,1, 2, 3, 4, 1, 2, 3, 4, 5, 6]
np.split(lst, np.where(np.diff(lst) < 0)[0] + 1)

# [array([1, 2, 2, 2]),
#  array([1, 2, 3, 3]),
#  array([1, 1, 1, 2, 3, 4]),
#  array([1, 2, 3, 4, 5, 6])]
+5

Psidom , NumPy scipy.signal.argrelmax , np.split.

from scipy.signal import argrelmax
arr = np.random.randint(1000, size=10**6)
splits = np.split(arr, argrelmax(arr)[0]+1)
+2

, :

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

First find the places where the splitting will occur:

p = [ i+1 for i, (x, y) in enumerate(zip(a, a[1:])) if x > y ]

Then create slices for each such split:

print [ a[m:n] for m, n in zip([ 0 ] + p, p + [ None ]) ]

This will print the following:

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

I suggest using a more descriptive names than p, n, metc .; -)

+1
source

Source: https://habr.com/ru/post/1669748/


All Articles