sam
sam

Reputation: 494

How to compare values in a list with a specific integer value?

I have a function which returns say either [1], [1,2],[1,2,3] or [1,2,3,4]. I want to compare the values inside the list with some value( say 0.2).

Before this, I had just an integer value coming from my function not a list of values to compare with 0.2.`

# this function gives a list as mentioned previously
iou_value = oneObject.intersection_over_union(image,humanPos,belongings_bb)     

if iou_value is not None and iou_value > 0.2:

How should I write the if condition in such a scenario to compare list values with 0.2?

Thanks

Upvotes: 0

Views: 1054

Answers (4)

manic.coder
manic.coder

Reputation: 93

Depends what exactly you want, but most likely list comprehension will help you:

compared_list = [1 for elem in iou_value if elem > 0.2 else 0]

Will give you 1 and 0 at corresponding indices

Edit: if you want to separate the elements based on the comparison:

geq = [elem for elem in iou_value if elem >= 0.2]
less = [elem for elem in iou_value if elem < 0.2]

Edit 2: if you want a simple loop with if-conditions:

for elem in iou_value:
    if elem >= 0.2:
        #do what you want if geq
    else:
        #do what you want if less

Upvotes: 2

Mayank Porwal
Mayank Porwal

Reputation: 34086

A simple if condition with would do this:

In [2090]: l = [1,2,3,4]

In [2091]: val = 0.2

In [2093]: for i in l:
      ...:     if i > val:
      ...:         print('{} is greater than {}'.format(i,val))
      ...:         
1 is greater than 0.2
2 is greater than 0.2
3 is greater than 0.2
4 is greater than 0.2

OR use list comprehensions:

In [2096]: ['yes' for i in l if i > val]
Out[2096]: ['yes', 'yes', 'yes', 'yes']

Upvotes: 1

Burhan Khalid
Burhan Khalid

Reputation: 174728

You need to loop through the list to compare each value, like this:

if iou_value is not None:
  for v in iou_value:
    if v > 0.2:
      print(f'{v} is greater than 0.2')

You may want to adjust your method so that instead of returning None, it returns an empty list [], this way you can also delete the if io_value is not None check.

Upvotes: 1

Rakesh
Rakesh

Reputation: 82795

You can use any()

Ex:

a = [1,2,3,4]

if any(iou_value > 0.2 for iou_value in a):
    print("Yes")
else:
    print("No")

Upvotes: 1

Related Questions