Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Split list in subsets if the current element is minor than previous element

I have the following python list:

my_list = [1, 2, 3, 1, 2, 1, 2, 3]

I am looking for a efficient way to split a list in several sublist only if the current element is minor than the previous element.

In the example, I should get:

result = [[1,2,3],[1,2],[1,2,3]]

I should get three subsets since 1<3 and 1<2.

I am only getting the first elements with this solution:

[[x] for index, x in enumerate(my_list) if index < 1 or x < my_list[index - 1]]

Result:

[[1], [1], [1]]

Another try with the same result:

[ [my_list[x]] for x in range(len(my_list)) if my_list[x] < my_list[x-1]]
like image 276
shakaran Avatar asked Nov 19 '25 05:11

shakaran


1 Answers

Here's a comprehension-ish approach. But while you could cram this into one long expression, why on Earth would you want to?

>>> my_list = [1, 2, 3, 1, 2, 1, 2, 3]
>>> brks = [i for i in range(1,len(my_list)) if my_list[i] < my_list[i-1]]
>>> [my_list[x:y] for x,y in zip([0]+brks,brks+[None])]
[[1, 2, 3], [1, 2], [1, 2, 3]]

This works simply by finding the points where a new group begins and using those to slice into my_list.

like image 187
DSM Avatar answered Nov 21 '25 18:11

DSM



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!