pythonarraysinequality

Seperate array into three new arrays using inequalities in Python


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]

Solution

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