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
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
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)
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
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
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)