Finding k closest numbers to a given number

后端 未结 3 727
太阳男子
太阳男子 2020-12-23 20:56

Say I have a list [1,2,3,4,5,6,7]. I want to find the 3 closest numbers to, say, 6.5. Then the returned value would be [5,6,7].

Finding one

3条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-23 21:31

    You could compute distances, and sort:

    [n for d, n in sorted((abs(x-myNumber), x) for x in myList)[:k]]
    

    This does the following:

    1. Create a sequence of tuples (d, x) where d is the distance to your target
    2. Select the first k elements of that list
    3. Extract just the number values from the result, discarding the distance

提交回复
热议问题