简体   繁体   中英

How to check a list for greater or less than var integers

var=42

l = [1,2,3,7,3,5,21,8,44,16,13]

if l.index(5) < l.index(var-20):
    print ("True")  

else:
    print ("False")

I want to pick a value (var) and test to see which comes first from the list, either var+ (for example 20), or var- (again could be 20).

The problem I am having with the above code is that if a value doesn't exist in the list, then it gives me an error telling me so.

You need a different approach to finding the numbers, obviously. Instead, let's try computing once the numbers you need to find. Let's assume different numbers for the spans, such as 20 high (what you used) and 17 low (for sake of difference).

var = 42
target = [1,2,3,7,3,5,21,8,44,16,13]

lo_diff = 20
hi_diff = 17

lo_num = var - lo_diff
hi_num = var + hi_diff

# Check to see which of the two is in the list:

lo_index = target.index(lo_num) if lo_num in target else -1
hi_index = target.index(hi_num) if hi_num in target else -1

This leaves you with the accurate index for each value found, -1 if not found. I expect that you can finish from here?


USAGE NOTE

Learn to believe in Boolean values. Your output block should be a single statement:

if l.index(5) < l.index(var-20):
    print ("True")  
else:
    print ("False")

... reduces to ...

print( l.index(5) < l.index(var-20) )

Simply print the value of the Boolean expression.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM