Home > Enterprise >  How can I split a list composed of number?
How can I split a list composed of number?

Time:11-23

Imagine there is a list composed of number such as

a = [1, 2, 3, 4, 10, 11, 12, 44, 45, 46, 47]

I want to split this list by difference of its elements like;

b = [1, 2, 3, 4] 
c = [10, 11, 12]
d = [44, 45, 46, 47]

CodePudding user response:

Here's a simple approach using a for loop. Assumptions made here are that the original list is sorted and that we're grouping based on a difference <= 1.

>>> a = [1, 2, 3, 4, 10, 11, 12, 44, 45, 46, 47]
>>> groups = [[a[0]]]
>>> for i in a[1:]:
...     if i - groups[-1][-1] > 1:
...         groups.append([i])
...     else:
...         groups[-1].append(i)
...
>>> groups
[[1, 2, 3, 4], [10, 11, 12], [44, 45, 46, 47]]
  • Related