0

I want to get 5 integers closest to 100, such as 100, 99,98, 101, 102 I have used the following methods, but have not got the desired result.

myList = [95,96,97,98,99,100,101,102,103,104,105]
for i in myList:
    print(min(myList, key=lambda x:abs(x-100)))
    myList.remove(i)

output:

100
100
100
100
100
100

Then I did this:

myList = [95,96,97,98,99,100,101,102,103,104,105]
for i in myList:
    print(min(myList, key=lambda x:abs(x-i)))
    myList.remove(i)

output:

95
97
99
101
103
105

In this case, more than 95, 97, and 105; the 98, 96 and 102 are closest; but instead, these closes numbers are skipped.

Please, have a look and come up with suggestions. Thanks :)

1 Answers1

2

You're just printing the minimum value (with respect to your definition), but then you're popping just the next element. Instead, do something like this:

myList = [95,96,97,98,99,100,101,102,103,104,105]
for i in range(5):  # we want 5 elements
    best = min(myList, key=lambda x: abs(100-x))
    myList.remove(best)
    print(best)

That prints:

100
99
101
98
102

But there's an easier way to get what you want. Just sort it and take the first n elements:

# prints [100, 99, 101, 98, 102]
print(sorted(myList, key=lambda x: abs(100-x))[:5])

The top answer to the duplicate question has an even better ((n)) solution:

from heapq import nsmallest
print(nsmallest(5, myList, key=lambda x: abs(100-x))
L3viathan
  • 26,748
  • 2
  • 58
  • 81