2

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!

Tendero
  • 1,136
  • 2
  • 19
  • 34

2 Answers2

0
def spacer(data, n=1):
    set(data)
    output = [[data[0]]]
    for i in data[1:]:
        if i - output[-1][-1] > n:
            output.append([i])
        else:
            output[-1].append(i)
    return output

data = [1, 2, 3, 6, 8, 10, 14, 15, 17, 20]
for i in range(1, 4):
    print("N={}, {}".format(i, spacer(data, n=i)))

output:

N=1, [[1, 2, 3], [6], [8], [10], [14, 15], [17], [20]]
N=2, [[1, 2, 3], [6, 8, 10], [14, 15, 17], [20]]
N=3, [[1, 2, 3, 6, 8, 10], [14, 15, 17, 20]]
C.Cheung
  • 31
  • 4
0

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]]
jizhihaoSAMA
  • 12,336
  • 9
  • 27
  • 49