Comparing variables in a list

Question:

I have a list of numbers:

x = [601.4, 603.6, 600.5, 605.7]

and when a value in the list is within +1 of another one, I want to set a boolean variable to true.

So this:

i = 0
while i < 4:
   if x[i] smart function here
      y = True
   else:
      y = False
   print (y)
   i = i + 1

would give out:

True
False
False
False
Asked By: SkyThaKid

||

Answers:

You could map the checking function f = lambda v: True if v - x[i] >= -1. and v - x[i] <= 0. else False on the list x[0:i] + x[i+1:] that excludes the current index. Finally, check the created iterable of the map result with any.

x = [601.4, 603.6, 600.5, 605.7]

i = 0
while i < 4:
    f = lambda v: True if v - x[i] >= -1. and v - x[i] <= 0. else False
    if any(map(f, x[0:i] + x[i+1:])):
        y = True
    else:
        y = False
    print (y)
    i = i + 1
Answered By: Holger

x = [601.4, 603.6, 600.5, 605.7]

for value in x:
    y = False
    for val in x:
        if val != value:
            if val < value < val + 1:
                y = True
                break
    print(y)

Answered By: Redsan16
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.