I have a list of variables [A1, A2, A3, A4, A5, A6, A7, A8, A9, A10]
to 1 decimal place. I have a variable B which can be any number to decimal place.
I would like to find the closest value in the list to variable B.
And return not the value but the A number(A5 for example).
Asked
Active
Viewed 2,734 times
0

Jean-François Corbett
- 37,420
- 30
- 139
- 188

Colin Wood
- 21
- 1
- 1
-
3Welcome Colin! What did you tried? Could you post your code and explain which problem do you have implementing this? – llrs May 21 '15 at 12:02
-
Do you actually want the _name_ of the variable, or the index in the list? The former will generally not be (easily) possible, but you could use a dictionary and return the key. – tobias_k May 21 '15 at 12:05
-
`values.index(min(values, key = lambda i : abs(B - i)))` – Cory Kramer May 21 '15 at 12:05
-
Breaking it down, you want the [index](https://docs.python.org/2/tutorial/datastructures.html) of the value in the list that has the least [difference](https://docs.python.org/2/library/functions.html#abs) to value B. Other hint: [for loop](https://wiki.python.org/moin/ForLoop) – Aeveus May 21 '15 at 12:07
3 Answers
1
from operator import itemgetter
a = [A1, A2, ........, A10]
minimum_list = [abs(variable - B) for variable in a]
return min(enumerate(minimum_list), key=itemgetter(1))[0]
This will return the index of the variable with the minimum difference.
return a[min(enumerate(minimum_list), key=itemgetter(1))[0]]
This will return the value in the list with the minimum difference with the variable B

Arpit Goyal
- 2,212
- 11
- 31
0
If you know numpy, you can write as this:
matA = array([A1, A2, A3, A4, A5, A6, A7, A8, A9, A10])
matB = array([B])
diff = abs(matA - matB)
minDiffValue = min(diff)
And then, write the code like this to find the index of the element:
closeValueIndex = []
index = 0
for i in diff:
if i == minDiffValue:
closeValueIndex.append(index)
index += 1

JUA
- 1
- 1
0
In [1]: vals = [0.8, 5.0, 10.2, 15.6]
value = lambda myvalue: min(vals, key=lambda x: abs(x - myvalue))
value(9.8)
Out[1]: 10.2
But if you want to return a non-numeric answer, to which I think you want. Just use the same but with a dictionary and the values as the keys, answers you want back as the values:
In [2]: vals = {0.8:'A1', 5.0:'A2', 10.2:'A3', 15.6:'A4'}
value = lambda myvalue: vals.get(min(vals, key=lambda x: abs(x - myvalue)))
value(9.8)
Out[2]: 'A3'

Patrick Hofman
- 153,850
- 22
- 249
- 325

Miles
- 1,104
- 11
- 13