Comparing Numbers in Multiple Lists Python

Issue

I have 5 sets of values that look like this:

[[83.91649562 79.51353257]
 [87.57474691 84.66544614]
 [84.08067077 85.19063777]
 [86.97440657 86.20994142]
 [82.91694642 84.65734125]]

My goal is to compare the two values within each set with this criteria:

  1. in any of the lists, if item1 and item2 are >= 80 AND item1 < item2, return -10
  2. in any of the lists, if item1 and item2 are <= 20 AND item1 > item2, return 10
  3. else return 0

Here’s what I’ve done

def myfunction(data):
    data = data.iloc[:, [0, 1]].values
    for x, y in enumerate(data):
        if (x-y).all() >= 80 and x < y:
            return -10
        else:
            return 0

Right now I’m returning 0, however the 3rd and 5th lists met the criteria and should have returned -10 so I haven’t moved on to the second if statement.
I’ve also tried setting up the data with:

data = data.iloc[:, [0, 1]].values.tolist()

to use the data as

[[83.91649561983937, 79.51353257164777], [87.57474691499445, 84.66544613660386], [84.08067077024245, 85.19063776835876], [86.97440656949847, 86.20994141824511], [82.91694641784167, 84.65734125252753]]

With no luck. I’ve been using enumarate() because I’ve had the most success with not getting error messages but I’m not sure if that’s necessarily what I need for this problem.

Thanks all!

Solution

Without using any library, For simplification you can write loop like this

#Devil
lst = [[83.91649562, 79.51353257],
    [87.57474691, 84.66544614],
    [84.08067077, 85.19063777],
    [86.97440657, 86.20994142],
    [82.91694642, 84.65734125]]

fill_out = []
for i in lst:
    #print(i)
    item1 = i[0] ; item2 = i[1]
    if item1 >= 80 and item2 >= 80 and item1 < item2:
        fill_out.append(-10)
    elif item1 <= 20 and item2 <= 20 and item1 > item2:
        fill_out.append(10)
    else:
        fill_out.append(0)

print("output:",fill_out)
#output : [0, 0, -10, 0, -10]

Answered By – Devil

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published