Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting list based on difference between consecutive elements

Tags:

python

list

I found this question that is related to mine. In that question a specific case is treated, and that's splitting a list of integers when a difference of more than 1 is present between consecutive elements.

I was wondering: is there way to make this work for a difference of N, a parameter? Namely, suppose we have this list:

[1,2,3,6,8,10,14,15,17,20]

For N=2, the output should be:

[[1,2,3], [6,8,10], [14,15,17], [20]]

For N=3, the output should be:

[[1,2,3,6,8,10], [14,15,17,20]]

And for N=4, the output should be the same input list.

I did it like this:

from itertools import takewhile

input_list = [1,2,3,6,8,10,14,15,17,20]
N = 4

def fun(l, N, output=[]):
    if len(l):
        output.append([x[1] for x in takewhile(lambda x: x[1]-x[0]<=N,
                                               zip([l[0]]+l, l))])
        fun(l[len(output[-1]):], N, output)
    return output

fun(input_list, N)

But I don't really like it: it's unreadable. Something stylish as a one-liner or something pretty pythonic would be appreciated!

like image 875
Tendero Avatar asked May 01 '26 21:05

Tendero


1 Answers

Two lines with list-comprehension:

def split_list(l, n):
    index_list = [None] + [i for i in range(1, len(l)) if l[i] - l[i - 1] > n] + [None]
    return [l[index_list[j - 1]:index_list[j]] for j in range(1, len(index_list))]

test:

example = [1, 2, 3, 6, 8, 10, 14, 15, 17, 20]
for i in range(2,5):
    print(split_list(example, i))

# [[1, 2, 3], [6, 8, 10], [14, 15, 17], [20]]
# [[1, 2, 3, 6, 8, 10], [14, 15, 17, 20]]
# [[1, 2, 3, 6, 8, 10, 14, 15, 17, 20]]
like image 170
jizhihaoSAMA Avatar answered May 04 '26 10:05

jizhihaoSAMA



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!