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 to split a list into sublists with specific range for each sublist?

I want to split a list into sublist with specific ‘if statement’ for each sublist.
For examle:
input:

a = [1, 2, 7.9, 3, 4, 3.7, 5, 6, 2.2, 7, 8, 1.2, 5.7]

output:

b = [[1, 1.2, 2], [2.2, 3, 3.7, 4], [5, 5.7, 6], [7, 7.9, 8]]

Values should be grouped by certain range. here it is between (1:2); (2.1:4); (4.1:6); (6.1:8). I hope I was able to get my point across.

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 :

You seem to want to divide your data into buckets of width dx. Assuming this, your expected output would be:

[[1, 1.2, 2], [2.2, 3], [3.7, 4], [5, 5.7, 6], [7, 7.9, 8]]

First, let’s sort the input numbers:

numbers = sorted(a)

Now, we’ll iterate over this sorted list, and append to a bucket list as long as appending the current number wouldn’t exceed our desired range for this bucket. If appending the current number would cause the desired range to be exceeded, then we create a new bucket and start appending to it:

bucket = []
result = [bucket]
for n in numbers:
    # bucket is empty, or bucket range <= dx, so append
    if not bucket or n - bucket[0] <= dx: 
        bucket.append(n)
    else:
        bucket = [n] # Create a new bucket with the current number
        result.append(bucket) # Add it to our result array

This gives your expected result:

result = [[1, 1.2, 2], [2.2, 3], [3.7, 4], [5, 5.7, 6], [7, 7.9, 8]]
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