taga
taga

Reputation: 3885

Splitting list with mathematical condition python

I want to write a code that will split the list (one time or more times) based on the mathematical condition . This is the list:

full_list = [1,2,4,6,7,10,12,13,20,22,23,26,36,37,39]

I want to split this list on the place where difference between two neighbor elements are more than 6. So, based on list above, output should be:

A_list = [1,2,4,6,7,10,12,13]
B_list = [20,22,23,26]
C_list = [36,37,39]

Upvotes: 0

Views: 57

Answers (3)

Christian Sloper
Christian Sloper

Reputation: 7510

This can be done quite easy with numpy:

import numpy as np

full_list = [1,2,4,6,7,10,12,13,20,22,23,26,36,37,39]
a = np.array(full_list)

np.split(a,np.argwhere(np.roll(np.diff(a) > 6,1)).reshape(-1))

This would yield:

 [array([ 1,  2,  4,  6,  7, 10, 12, 13]),
 array([20, 22, 23, 26]),
 array([36, 37, 39])]

If you want to go back to normal lists like this:

list(map(list,result))

Upvotes: 2

blhsing
blhsing

Reputation: 106523

You can pair adjacent items by zipping the list with itself but pad one of them with negative infinity so the difference with it is guaranteed to be greater than 6, and then build a list of lists accordingly:

lists = []
for a, b in zip([float('-inf')] + full_list, full_list):
    if b - a > 6:
        lists.append([])
    lists[-1].append(b)

lists would become:

[[1, 2, 4, 6, 7, 10, 12, 13], [20, 22, 23, 26], [36, 37, 39]]

And if you're sure that your list is always going to be splitted into exactly 3 lists, you can unpack them into 3 variables as you wish in the question:

A_list, B_list, C_list = lists

Upvotes: 0

Uli Sotschok
Uli Sotschok

Reputation: 1236

If you don't want to use numpy you can try the following:

full_list = [1, 2, 4, 6, 7, 10, 12, 13, 20, 22, 23, 26, 36, 37, 39]
split_lists = []
prev_val = full_list[0]
last_split = 0
for idx, val in enumerate(full_list[1:]):
    if abs(prev_val - val) > 6:
        split_lists.append(full_list[last_split:idx + 1])
        last_split = idx + 1
    prev_val = val
split_lists.append(full_list[last_split:])
print(split_lists)

Upvotes: 0

Related Questions