I should append a number x
in a list called y
if in y
there are not number that are in the neighbourhood of x
.
For example, if I have:y = [1, 1.5, 1.7, 2.1, 3]
i need to append a number that is not in the range /-0.1 of the number in the list.
So I will append x = 3.2
but not append x =3.05
CodePudding user response:
I don't know if the range condition applies to all the list elements or only the last one, here's the example of both:
def foo(lst:list, value, dif=0.1):
clos = min(lst, key=lambda lst : abs(lst - value))
if abs(clos - value) > dif:
lst.append(value)
return lst
foo(y, 3.2)
Output: [1, 1.5, 1.7, 2.1, 3, 3.2]
Or only to last element:
def foo(lst:list, value, dif=0.1):
if abs(value - lst[-1]) > dif:
lst.append(value)
return lst
CodePudding user response:
What you are looking for is probably np.isclose
# For x = 3.2
>>> ~np.isclose(y, x, atol=0.1).any()
True
# For x = 3.05
>>> ~np.isclose(y, x, atol=0.1).any()
False