Find multiple values ​​in python array close to given number

Using Python 2.7, I have an array of values ​​from ~ 0.000 to ~ 360.000 several times. I am trying to return all array indices with values ​​close to 147.010 (even duplicate values), so later I can use each of these indices. For example, a smaller selection from a single array:

array([  146.749,  147.249,  147.749,  146.749,  147.249,  147.749,  146.749,  147.263,  147.749,  146.472,  147.469,  148.471])

I am looking for an array or list of indexes closest to 147.01, in this case would be:

1, 4, 7, 10

I tried this:

min(range(len(array)), key=lambda i: abs(array[i]-some_value))

but this only returns one index when multiple indexes are required. I looked, but did not find a similar question or answer. Thanks for any help.

+4
source share
3 answers

, , k , , ,

def k_closest(sample, pivot, k):
    return sorted(sample, key=lambda i: abs(i - pivot))[:k]

:

>>> l = [1,2,3,4]
>>> k_closest(l, 3, 2)
[3,2]
>>> k_closest(l, 3, 3)
[3,2,4]

, :

def k_closest(sample, pivot, k):
    return sorted(enumerate(sample), key=lambda (n, v): abs(v - pivot))[:k]

, ,

>>> l = [1,2,3,4]
>>> k_closest(l, 3, 2)
[(2, 3), (1, 2)]
>>> k_closest(l, 3, 3)
[(2, 3), (1, 2), (3, 4)]

- , - ,

, ,

import operator

def k_closest(sample, pivot, k):
    return map(operator.itemgetter(0), sorted(enumerate(sample), key=lambda (n, v): abs(v - pivot)))[:k]

>>> k_closest(l, 3, 2)
[2, 1]
>>> k_closest(l, 3, 3)
[2, 1, 3]
+3

, . , , .

new_array = map(lambda x: abs(x-some_value),my_array)

min_value=min(new_array)

my_keys = []
for i,val in enumerate(new_array):
    if val == min_value:
        my_keys.append(i)

, .

my_answer=[]
for i in my_keys:
    my_answer.append(my_array[i])
0

, k = 147.01, :

print [i for i, v in enumerate(array) if abs(v - k) == min([abs(x - k) for x in array])]

: [1, 4]

It will print as many n element indices as possible close to k. Your list items with index 7, 10 are not equally close, can you double check these numbers?

EDIT . Look one by one using the array from the question:

[146.749,  147.249,  147.749,  146.749,  147.249,  147.749,  146.749,  147.263,  147.749,  146.472,  147.469,  148.471]

Distances for items with indices: 1, 4, 7, 10:

index = 1,  abs(147.249 - 147.01) = 0.239
index = 4,  abs(147.249 - 147.01) = 0.239
index = 7,  abs(147.263 - 147.01) = 0.253
index = 10, abs(147.469 - 147.01) = 0.459

In accordance with these numbers, elements in indices 1, 4have a shorter distance from 147.01than 7, 10. Isn't that what you had in mind?

0
source

All Articles