-1

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]
1
  • In your code, measurement is the whole original list so you are assigning the whole list to small, medium, large. You should be adding the element that you are comparing (x) to these lists. Please check the Python documentation about lists and specifically list.append(). Commented Dec 13, 2021 at 0:32

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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]}

Comments

0

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': []}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.