Home > Enterprise >  Seperate array into three new arrays using inequalities in Python
Seperate array into three new arrays using inequalities in Python

Time:12-13

I am trying to split an array into three new arrays using inequalities.

This will give you an idea of what I am trying to achieve:

measurement = [1, 5, 10, 13, 40, 43, 60]

for x in measurement:
    if 0 < x < 6:
        small = measurement
    elif 6 < x < 15:
        medium = measurement
    else
        large = measurement

Intended Output:

small = [1, 5]
medium = [10, 13]
large = [40, 43, 60]

CodePudding user response:

If your array is sorted, you can do :

measurement = [1, 5, 10, 13, 40, 43, 60]
one_third = len(measurement) // 3
two_third = (2 * len(measurement)) // 3

small = measurement[:one_third]
medium = measurement[one_third : two_thirds]
large = measurement[two_thirds:]

You could easily generalize to any number of split with a loop. Not sure if you wanted explicitly those inequalities or just split with the array in three. If its the first one, my answer is not right

CodePudding user response:

You can use numpy:

arr = np.array(measurement)     
small = arr[(arr>0)&(arr<6)]    # array([1, 5])
medium = arr[(arr>6)&(arr<15)]  # array([10, 13])
large = arr[(arr>15)]           # array([40, 43, 60])

You can also use dictionary:

d = {'small':[], 'medium':[], 'large':[]}
for x in measurement:
    if 0 < x < 6:
        d['small'].append(x)
    elif 6 < x < 15:
        d['medium'].append(x)
    else:
        d['large'].append(x)

Output:

{'small': [1, 5], 'medium': [10, 13], 'large': [40, 43, 60]}

CodePudding user response:

With the bisect module you can do something along these lines:

from bisect import bisect
breaks=[0,6,15,float('inf')]
buckets={}

m = [1, 5, 10, 13, 40, 43, 60]

for e in m:
    buckets.setdefault(breaks[bisect(breaks, e)], []).append(e)

You then have a dict of lists matching what you are looking for:

>>> buckets
{6: [1, 5], 15: [10, 13], inf: [40, 43, 60]}

You can also form tuples of your break points and list that will become a dict to form the sub lists:

m = [1, 5, 10, 13, 40, 43, 60]
buckets=[('small',[]), ('medium',[]), ('large',[]), ('other',[])]

breaks=[(0,6),(6,15),(15,float('inf'))]

for x in m:
    buckets[
        next((i for i,t in enumerate(breaks) if t[0]<=x<t[1]), -1)
           ][1].append(x)

>>> dict(buckets)
{'small': [1, 5], 'medium': [10, 13], 'large': [40, 43, 60], 'other': []}
  • Related