0

I've seen from list of integers, get number closest to a given value and finding index of an item closest to the value in a list that's not entirely sorted, but neither of them cover how to find closest values if there are multiple.

Example:

>>> myList = [1, 4, 5, 9, 10, 12, 15, 17]
>>> min(myList, key=lambda x: abs(x - 16))
15  # How could I get both 17 and 15?
Azat Ibrakov
  • 9,998
  • 9
  • 38
  • 50
KetZoomer
  • 2,701
  • 3
  • 15
  • 43
  • 1
    have you tried [`heapq.nsmallest`](https://docs.python.org/3/library/heapq.html#heapq.nsmallest)? – Azat Ibrakov Jul 11 '21 at 16:48
  • @AzatIbrakov could you post an answer with an example of using it! It would be very much appreciated! Thank you link also! – KetZoomer Jul 11 '21 at 16:59

2 Answers2

4

To find more than 1 minimum value we can use heapq.nsmallest function like

>>> myList = [1, 4, 5, 9, 10, 12, 15, 17]
>>> from heapq import nsmallest
>>> nsmallest(2, myList, key=lambda x: abs(x - 16))
[15, 17]
Azat Ibrakov
  • 9,998
  • 9
  • 38
  • 50
2

You could make a dictionary that maps distances to values, then return the values with the minimal distance like so:

from collections import defaultdict

d = defaultdict(list)

# {distance: [values]}
for i in myList:
    d[abs(i-16)].append(i)

d[min(d)] # Result: [15, 17]
furas
  • 134,197
  • 12
  • 106
  • 148
fsimonjetz
  • 5,644
  • 3
  • 5
  • 21