Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I split a list composed of number?

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]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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]]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading